正如您在本视频中看到的,对象在任何方向上移动,但其模型不沿移动方向旋转。如何修复??
链接到视频
https://youtu.be/n4FDFDlsXK4
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveController : MonoBehaviour
{
private CharacterController controller = null;
private Animator animator = null;
private float speed = 5f;
void Start()
{
controller = gameObject.GetComponent<CharacterController>();
animator = gameObject.GetComponent<Animator>();
}
void Update()
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = (transform.right * x) + (transform.forward * z);
controller.Move(move * speed * Time.deltaTime);
var angle = Mathf.Atan2(move.z, move.x) * Mathf.Rad2Deg;
if (x != 0 || z != 0) animator.SetTrigger("run");
if (x == 0 && z == 0) animator.SetTrigger("idle");
}
}
不要使用transform.forward
和transform.right
来制作移动向量,只需在世界空间中制作即可。然后,可以将transform.forward
设置为移动方向。
此外,正如德雨果在下面的评论中提到的,你应该
-
避免使用精确相等来比较浮点值。相反,使用
Mathf.Approximately
或使用自己的阈值,如低于 -
避免设置每个帧的触发器。相反,您可以使用一个标志来确定您是否已经空闲或正在运行,并且只有在您还没有做这件事时才设置触发器。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MoveController : MonoBehaviour
{
private CharacterController controller = null;
private Animator animator = null;
private float speed = 5f;
bool isIdle;
void Start()
{
controller = gameObject.GetComponent<CharacterController>();
animator = gameObject.GetComponent<Animator>();
isIdle = true;
}
void Update()
{
float x = Input.GetAxis("Horizontal");
float z = Input.GetAxis("Vertical");
Vector3 move = new Vector3(x, 0f, z);
controller.Move(move * speed * Time.deltaTime);
var angle = Mathf.Atan2(move.z, move.x) * Mathf.Rad2Deg;
if (move.magnitude > idleThreshold)
{
transform.forward = move;
if (isIdle)
{
animator.SetTrigger("run");
isIdle = false;
}
}
else if (!isIdle)
{
animator.SetTrigger("idle");
isIdle = true;
}
}
}