c# - 我遵循了有关在统一上为 fps 游戏制作控件的教程。控件可以工作,但是如果我离开控件,那么我会继续向左移动
问题描述
在此处输入图像描述我为我的角色制作了沿 X 轴移动的控件。他们似乎工作正常,但我的角色一直向左移动,我不确定为什么或错过了什么。我已经发布了来自两个单独脚本的代码
我已经多次重新检查他的代码。我检查了我的箭头键、数字键盘键和 WASD 是否粘住或其他任何东西。
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class PlayerMotor : MonoBehaviour
{
private Vector3 velocity = Vector3.zero;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
//gets a movement vector
public void Move (Vector3 _velocity)
{
velocity = _velocity;
}
//run every physics iteration
void FixedUpdate()
{
PerformMovement();
}
//perform movement based on velocity variable
void PerformMovement ()
{
if (velocity != Vector3.zero)
{
rb.MovePosition(rb.position + velocity * Time.fixedDeltaTime);
}
}
}
和控制器:
using UnityEngine;
[RequireComponent(typeof(PlayerMotor))]
public class PlayerController : MonoBehaviour
{
[SerializeField] //makes speed show up in inspector even if set to private
private float speed = 5f;
private PlayerMotor motor;
void Start ()
{
motor = GetComponent<PlayerMotor>();
}
void Update()
{
//Calculate movement velocity as a 3D vector
float _xMov = Input.GetAxisRaw("Horizontal");
float _zMov = Input.GetAxisRaw("Vertical");
Vector3 _movHorizontal = transform.right * _xMov;
Vector3 _movVertical = transform.forward * _zMov;
//final movement vector
Vector3 _velocity = (_movHorizontal + _movVertical).normalized * speed;
//apply movement
motor.Move(_velocity);
}
}
我希望在不按下按钮时输出 0,但它似乎让我以 5 的速度向左移动
解决方案
您连接了一个控制器并报告了一个方向的轻微移动。使用Input.GetAxis
而不是Input.GetAxisRaw
让 Unity 处理死区检测。这样,几乎中性的输入将被视为中性输入。
void Update()
{
//Calculate movement velocity as a 3D vector
float _xMov = Input.GetAxis("Horizontal");
float _zMov = Input.GetAxis("Vertical");
Vector3 _movHorizontal = transform.right * _xMov;
Vector3 _movVertical = transform.forward * _zMov;
//final movement vector
Vector3 _velocity = (_movHorizontal + _movVertical).normalized * speed;
//apply movement
motor.Move(_velocity);
}
推荐阅读
- javascript - 使用 javascript、mysql、php 和 html 打印包含工资计算的网页
- github - 将 Slack webhook 连接到 GitHub
- python - 如何遍历字典列表并打印特定键的值?
- angularjs - .then 中的期望条件不会执行
- performance - 基准测试 - 如何计算发送到 CPU 的指令数以查找消耗的 MIPS
- php - php在没有相对路径的绝对url中转换包含相对路径的绝对url
- azure - 在 Azure 上设置 Jenkins、Docker、Kubernetes ci/cd
- javascript - 在javascript中比较两个相同的字符串失败
- sql - 查询将比递归 cte 执行得更好
- php - 在变量中添加 wp_insert_post() 重要吗?