团结.如何将玩家转向运动方向



正如您在本视频中看到的,对象在任何方向上移动,但其模型不沿移动方向旋转。如何修复??

链接到视频

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.forwardtransform.right来制作移动向量,只需在世界空间中制作即可。然后,可以将transform.forward设置为移动方向。

此外,正如德雨果在下面的评论中提到的,你应该

  1. 避免使用精确相等来比较浮点值。相反,使用Mathf.Approximately或使用自己的阈值,如低于

  2. 避免设置每个帧的触发器。相反,您可以使用一个标志来确定您是否已经空闲或正在运行,并且只有在您还没有做这件事时才设置触发器。

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;
}
}
}

最新更新