简体   繁体   English

Unity3D角色朝向其移动方向

[英]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. 由于您的moveDirection已标准化,因此必须将其添加到当前位置才能在对象的本地空间中获取moveDirection。 Then you can LookAt() it to point towards it. 然后,您可以LookAt()指向它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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