Home > Mobile >  Unity 3D instantly rotate in the direction of movement
Unity 3D instantly rotate in the direction of movement

Time:11-24

I have a somewhat similar question to enter image description here

Here's forward: enter image description here

Here's left: enter image description here

Here's back: enter image description here

here's code attempt 1:

public void playerMovement()
    {
        float horizontalInput = Input.GetAxis("Horizontal");
        float verticalInput = Input.GetAxis("Vertical");

        Vector3 movementx = new Vector3(horizontalInput, 0f, 0f);
        Vector3 movementy = new Vector3(0f, 0f, verticalInput);
      
        movementy = transform.forward * verticalInput;
        movementx = transform.right * horizontalInput;

        if (horizontalInput > 0)
        {
            transform.eulerAngles = new Vector3(0f, 90f, 0f);
            transform.Translate(-movementx.normalized * 0.1f, Space.Self);
        }

        if (horizontalInput < 0)
        {
            transform.eulerAngles = new Vector3(0f, 270f, 0f);
            transform.Translate(-movementx.normalized * 0.1f, Space.Self);
        }

        if (verticalInput < 0)
        {
            transform.eulerAngles = new Vector3(0f, 180f, 0f);
            transform.Translate(movementy.normalized * 0.1f, Space.Self);
        }

        if (verticalInput > 0)
        {
            transform.eulerAngles = new Vector3(0f, 0f, 0f);
            transform.Translate(movementy.normalized * 0.1f, Space.Self);
        }
    }

Here's code attempt 2:

    public void playerMovement2()
    {
        Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));
        movement = transform.TransformDirection(movement);
        transform.Translate(movement.normalized * 0.1f, Space.Self);
        transform.rotation = Quaternion.LookRotation(movement);
    }

CodePudding user response:

I took your second attempt and modified it:

This way you will walk and look in the direction you

void Update()
{
    Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));

    transform.Translate(movement.normalized * 0.1f, Space.World);
    transform.rotation = Quaternion.LookRotation(movement, Vector3.up);

}

However then the character will always "flip" back to forward -> you can solve that by only moving when new input is given

For example like this:

void Update()
{
    Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical"));

    if (movement.magnitude > 0f)
    {
        transform.Translate(movement.normalized * 0.1f, Space.World);
        transform.rotation = Quaternion.LookRotation(movement, Vector3.up);
    }
}
  • Related