2

I am making a robot battling game where I want the enemy to randomly move and then sometimes travel towards the enemy. Code that I want the movement to be in.

else if (avoid == false)
        {
            transform.LookAt(target);
            transform.Translate(Vector3.forward * Time.deltaTime * movementSpeed);
            currentLerpTime = 0;
        }

This code just makes the AI move towards the player but I also want it occasionally to move in a random direction and then change direction occasionally. How would I do this?

  • 1
    Eeer...generally you'll want to have already attempted to solve the problem yourself, before asking for help on Stack Overflow. Try looking online on the best way to generate a random Vector3 in Unity, and consider using a FSM to manage the different states accordingly (randomly moving, approaching, attacking, etc.). It may take a little while to learn how to use one, but it's well worth it if you're developing games. – Serlite Aug 10 '16 at 17:32
  • There is a tutorial in Unity web site exactly for you. https://unity3d.com/learn/tutorials/topics/scripting/using-interfaces-make-state-machine-ai – Çağatay Kaya Aug 10 '16 at 18:46

1 Answers1

1

To make it move in a random direction, the variable you need to edit is the vector.

else if (avoid == false)
        {
            transform.LookAt(target);
            transform.Translate(Vector3.forward*Time.deltaTime*Speed);
                                 // ^^^^^^
            currentLerpTime = 0;
        }

The problem here though is while it moves it will continue to keep looking at the target (i am assuming this is getting called each frame). In terms of generating three random numbers, you can do this by yourself with just C# or go read this

https://docs.unity3d.com/ScriptReference/Random.html

That link should really help you out.

Hope this helps.

TheNoob
  • 861
  • 2
  • 11
  • 25