Enemy face direction of travel

I want the object or zombie in this case to face the direction of is movement, I have a script that cause random movements for the zombie but it never faces the direction of travel

    var speed : Vector3;
    var timing :float;
    function Start() {
       speed = Vector3(Random.Range(-359, 359),0,Random.Range(-359, 359));
       timing = 0;
    }
    function FixedUpdate() {
       timing+=Time.deltaTime;
       rigidbody.MovePosition(rigidbody.position + speed * Time.deltaTime);
        if(timing > 3){
           ChangeDirection();
           timing = 0;
        }
    }
    function ChangeDirection () {
        speed = new Vector3(Random.Range(-359, 359),0,Random.Range(-359, 359),0);  }

Please use code tags when posting code so that it is more readable for those trying to help you. See the link below for more information:

Sorry new here, fixed :slight_smile:

You have to rotate it to face the direction in which he is moving. So every time you change the direction he is moving you rotate him so he will face it

How do I calculate where he is facing?
transform.Lookat(?);

I don’t know what he has to look at

Thanks for all the help

Anyone know how to calculate the direction he will be going so I can face him that way?

Thank you

Vector3 newPos = rigidBody.position + speed * Time.deltaTime;
transform.LookAt(newPos);
rigidBody.MovePosition(newPos);
1 Like

Noob here don’t really know how to implement that in the code in JavaScript

Sorry guys I’m still so lost on this, only been on unity two weeks

90% of what I wrote is from your own code. Replacing Vector3 newPos with var newPos should work fine.

So I just add all that in? In the fixed update ? And the change direction?

Yes. You’re going to want to evaluate that every time. For a Javascript variable, use var instead of Vector3. Other than that, the code should work.
And yes, put it in fixed update.

1 Like
#pragma strict

var speed : Vector3;
var timing :float;
    function Start()
    {
       speed = Vector3(Random.Range(-5, 5),0,Random.Range(-5, 5));
       timing = 0;
    }
    function FixedUpdate()
    {
        timing+=Time.deltaTime;
        rigidbody.MovePosition(rigidbody.position + speed * Time.deltaTime);
        var newPos = rigidbody.position + speed * Time.deltaTime;
        transform.LookAt(newPos);
        rigidbody.MovePosition(newPos);
        if(timing > 3)
        {
           ChangeDirection();
           timing = 0;
        }
    }
    function ChangeDirection ()
        {
        speed = new Vector3(Random.Range(-5, 5),0,Random.Range(-5,5 ));
        }

thank you so much guys exactly what i needed, if anyone wants this, it works :slight_smile:

Just change the -359,359 in all places to alter speed