C# 面向移动方向的Unity3D角色
我正在制作一个游戏,它包含行星引力,我如何才能让玩家看到它移动的方向,如果我能将它插入到我的移动代码中,那会很有帮助C# 面向移动方向的Unity3D角色,c#,unity3d,C#,Unity3d,我正在制作一个游戏,它包含行星引力,我如何才能让玩家看到它移动的方向,如果我能将它插入到我的移动代码中,那会很有帮助 using UnityEngine; public class PlayerMovementScript : MonoBehaviour { public float moveSpeed; private Vector3 moveDirection; void Update() { moveDirection = new Vector3(Input.GetAxis
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);
}
}
假设此脚本已附加到要使点指向其移动方向的对象,请尝试以下操作
void Update()
{
moveDirection = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical")).normalized;
Vector3 lookDirection = moveDirection + gameObject.Transform.Position;
gameObject.Transform.LookAt(lookDirection);
}
由于moveDirection已规范化,因此必须将其添加到当前位置,以便在对象的局部空间中获得moveDirection。然后你可以看着它指向它 你可以使用刚体的速度来观察你移动的方向
transform.rotation = Quaternion.LookRotation(rb.velocity);
如果要平滑过渡,请执行以下操作:
Quaternion desiredRotation = Quaternion.LookRotation(rb.velocity);
transform.rotation = Quaternion.Slerp(transform.rotation, desiredRotation, Time.deltaTime);
你试过使用这种方法吗?您可以将moveDirection+gameObject.transform.position传递给它,它应该可以工作。使用Input.GetAxisRawHorizontal或← → 旋转或控制方向和输入。GetAxisRawVertical或↑ ↓ “控制运动。”Paul Jan说链接没有刚体。OP使用的是刚体。@程序员不管标题的细节如何,公认的答案也提到了如何使用刚体。但是你是对的,删除了接近的建议。这是有效的,除非我想旋转播放器,而不是相机。这应该旋转播放器,除非你的PlayerMovementScript连接到相机,这没有多大意义。然而,即使是这样,它也应该是一个简单的修复方法。可能是因为我的相机连接了,或者是因为播放器没有跟随脚本。你是什么意思?基本上,只要这个脚本附加到播放器本身,它就应该按预期工作。