Farhan Ali
Farhan Ali

Reputation: 509

how to make player in direction, in which he walking unity3d

my game is top down view, I am able to move character through joystick, now I want to make character looks in direction he walking to...don't know where to start, and write code, any suggestions here is my code..

void FixedUpdate()
{
    var inputDevice = InputManager.ActiveDevice;

    if (inputDevice != InputDevice.Null && inputDevice != TouchManager.Device)
    {
        TouchManager.ControlsEnabled = false;
    }
    float horizontal = inputDevice.Direction.X;
    float vertical = inputDevice.Direction.Y;
    if (cam != null) //if there is a camera
    {
        camForward = Vector3.Scale(cam.up, new Vector3(1, 0, 1)).normalized;
        move = vertical * camForward + horizontal * cam.right;
    }
    else
    {
        move = vertical * Vector3.forward + horizontal * Vector3.right;
    }

    if (move.magnitude > 1) //Make sure that the movement is normalized
        move.Normalize();

    Move(move);
    Vector3 movement = new Vector3(horizontal, 0, vertical);    
    if (horizontal == 0 && vertical == 0)
    {
        rigidBody.velocity = Vector3.zero * 0.5f;
    }


    rigidBody.AddForce(movement * speed / Time.deltaTime);
    transform.LookAt (movement); // I tried this, but character looks in mid only (0,0.4,0)
}

edit : transform.LookAt (movement); // I tried this, but character looks in mid only

Upvotes: 0

Views: 59

Answers (1)

KYL3R
KYL3R

Reputation: 4073

LookAt "looks" at a position, not a direction. Your movement is a direction relative to player position. Try this:

transform.LookAt (transform.position + movement.normalized);

Upvotes: 1

Related Questions