c# - 刚体.AddForce() 不会让我的玩家每次都统一跳到相同的高度
问题描述
所以我制作了一个带有刚体和一个子游戏对象“脚”的玩家,我还在我的玩家可以跳下的每个平台上添加了一层“地板”,这样我就可以使用 Physics.CheckSphere() 来查看我的玩家是否真的在地面,可以跳跃。在最后一种情况下,我使用 ForceMode.Impulse 向我的刚体添加一个力。一切正常,除了有时玩家跳一点点,有时跳得更高。这是我的代码:
[SerializeField] private float speed;
[SerializeField] private float jumpForce;
[SerializeField] private Transform feet = null;
[SerializeField] private LayerMask floorMask;
private Vector3 direction;
private Rigidbody rb;
void Start()
{
rb = GetComponent<Rigidbody>();
}
void Update()
{
direction = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical")) * speed;
transform.LookAt(transform.position + new Vector3(direction.x, 0, direction.z));
}
void FixedUpdate()
{
rb.velocity = new Vector3(direction.x, rb.velocity.y, direction.z);
if (Input.GetKeyDown(KeyCode.Space))
{
if (Physics.CheckSphere(feet.position, 0.1f, floorMask))
{
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
}
}
}
我用速度替换了 AddForce 方法,它似乎有效,但 AddForce 不是进行跳跃的正确方法?
rb.velocity = new Vector3(rb.velocity.x, 1 * jumpForce, rb.velocity.z);
解决方案
使用 ForceMode.Impulse 是使用 RigidBody 实现跳跃的理想方式。我相信您需要将按钮输入从 FixedUpdate() 中取出并将其放入常规 Update() 中。然后使用诸如“canJump”之类的布尔值。这是因为您的输入是在 FixedUpdate(); 中读取的。仅使用物理引擎每隔一帧调用一次。此外,您的 rb.velocity.y 在接触地面时应设置为 0。
void Update() {
direction = new Vector3(Input.GetAxis("Horizontal"), 0f, Input.GetAxis("Vertical")) * speed;
transform.LookAt(transform.position + new Vector3(direction.x, 0, direction.z));
bool canJump = Input.GetKeyDown(keyCode.Space) ? true : false;
}
void FixedUpdate() {
if (Physics.CheckSphere(feet.position, 0.1f, floorMask)) {
if (canJump)
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
else
rb.velocity = new Vector3(direction.x, 0, direction.z);
}
else
rb.velocity = new Vector3(direction.x, rb.velocity.y, direction.z);
}
推荐阅读
- c# - 如何生成没有重复值的字典?
- c# - 删除矩阵的边框
- javascript - 使用 JS 去除嵌入的 url
- vue.js - 为什么我的 vuejs 组件的挂载钩子不能引用同一组件中的某些方法?
- symfony - Symfony 4 生产 WebProfiler 路由
- c# - WPF 根据数据上下文值隐藏和显示按钮
- java - XSD“属性已定义”
- c# - 刚刚分配对象时的 Unity NullReferenceException
- python - X[y==0,1] 操作在代码中做了什么?
- rust - Rust 函数返回包含参数引用的对象编译正常,但当 &self 包含在参数列表中时编译失败