简体   繁体   中英

Unity3D character facing in the direction it’s moving

I am making a game, it contains planetary gravity, how would I be able to make the player look in the direction it's moving, would be helpful if I could insert it to my movement code

using UnityEngine;

public class PlayerMovementScript : MonoBehaviour {

public float moveSpeed;

private Vector3 moveDirection;

void Update()
{
    moveDirection = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;
}

void FixedUpdate()
{
    GetComponent<Rigidbody>().MovePosition(GetComponent<Rigidbody>().position + transform.TransformDirection(moveDirection) * moveSpeed * Time.deltaTime);
}
}

You can look in the direction you're moving by using the rigidbody's velocity.

transform.rotation = Quaternion.LookRotation(rb.velocity);

If you want a smoothed transition:

Quaternion desiredRotation = Quaternion.LookRotation(rb.velocity);
transform.rotation = Quaternion.Slerp(transform.rotation, desiredRotation, Time.deltaTime);

Assuming that this script is attached to the object you want to have point at its movement direction, try this.

void Update()
{
    moveDirection = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;
    Vector3 lookDirection = moveDirection + gameObject.Transform.Position;
    gameObject.Transform.LookAt(lookDirection);
}

Because your moveDirection is normalized, you have to add it to your current position in order to get the moveDirection in the object's local space. Then you can LookAt() it to point towards it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM