使用平移功能跳转的问题 [Unity 2D]



所以,我正在尝试编写一个简单的平台游戏作为类的工作,我在跳跃时遇到了问题,角色实际上跳跃了,但它似乎是一个瞬移,因为它立即到达跳跃的顶峰然后逐渐下降,我想让它更流畅。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class playerMovement : MonoBehaviour {
public float speed;
public float jumpForce;
public bool grounded;
public Transform groundCheck;
private Rigidbody2D rb2d;
// Use this for initialization
void Start () {
rb2d = GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update () {
}
private void FixedUpdate()
{
float moveVertical = 0;
float moveHorizontal = Input.GetAxis("Horizontal") * speed;
moveHorizontal *= Time.deltaTime;
grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
if (grounded && Input.GetKeyDown("space"))
{
moveVertical = Input.GetAxis("Jump") * jumpForce;
moveVertical *= Time.deltaTime;
}
Vector2 move = new Vector2(moveHorizontal, moveVertical);
transform.Translate(move);
}
}

但是,对于未来在 Unity 论坛上提出的与 Unity 相关的问题,问题的答案如下。随着越来越多的人专注于Unity本身,您将更快地得到更好的答案。

要固定跳跃,请将垂直和水平运动分成两部分,并使用您在 Start(( 函数中分配的刚体来处理跳跃。使用 ForceMode.Impulse 获得瞬间爆发的速度/加速度。

private void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal") * speed;
moveHorizontal *= Time.deltaTime;
grounded = Physics2D.Linecast(transform.position, groundCheck.position, 1 << LayerMask.NameToLayer("Ground"));
if (grounded && Input.GetKeyDown("space"))
{
rb2d.AddForce(transform.up * jumpForce, ForceMode.Impulse);
}
Vector2 move = new Vector2(moveHorizontal, 0);
transform.Translate(move);
}

与其在跳跃时设置位置,不如通过以下方式为角色的刚性身体添加垂直冲动:

if (grounded && Input.GetKeyDown("space"))
{
moveVertical = Input.GetAxis("Jump") * jumpForce;
moveVertical *= Time.fixedDeltaTime;
rb2d.AddForce(moveVertical, ForceMode.Impulse);
}
Vector2 move = new Vector2(moveHorizontal, 0f);

这将允许Rigidbody2D处理更改每帧垂直速度的工作。

另外,由于您是在FixedUpdate中进行所有这些计算的,而不是Update,因此使用Time.deltaTime是没有意义的。您应该改用Time.fixedDeltaTime

最新更新