c# - 统一。如何使玩家转向运动方向
问题描述
正如您在此视频中看到的,对象向任何方向移动,但其模型不会沿移动方向旋转。如何解决?
视频链接
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
andtransform.right
来制作你的移动向量,只需在世界空间中制作它。然后,您可以设置transform.forward
移动方向。
此外,正如derHugo在下面的评论中提到的,您应该
避免使用完全相等来比较浮点数。而是使用
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;
}
}
}
推荐阅读
- laravel - 使用 GET 方法进行请求验证在 Laravel 8 中不起作用 - Recaptcha
- php - 加载页面时未定义的索引
- javascript - 如果浏览器语言不是俄语,则重定向到英文版本
- email - 如何处理已读回执、送达回执和退回(JavaMail)
- uiimage - UIGraphicsPopContext():MacOS NSImage 等效于 Core Graphics?
- amazon-web-services - 使用具有严格白名单的公有子网与对 AWS 云资源使用私有子网的缺点
- angular - 未找到 Angular 通用 HTTP 404 资产
- android - 调用 requestDismissKeyguard() 两次,结果延迟
- python - 使用 * 运算符和多个变量格式化字符串
- nestjs - 多对一关系:在更改时更新父级