簡體   English   中英

Unity Engine: 2D Rigid body 添加運動后下落緩慢?

[英]Unity Engine: 2D Rigid body is falling slowly after adding movement?

我試圖將簡單的運動放入一個項目中,但由於某種原因,這導致它所應用的對象下落速度極慢。 我正在使用較新的輸入系統,但我以前並沒有真正使用過它,所以我不確定這是否是一個錯誤。

到目前為止,該運動正在按預期進行。 重力在設置中是默認的。

public class Movement : MonoBehaviour
{
    public Rigidbody2D rb;

    public float moveSpeed = 4f;
    public InputAction playerControl;

    Vector2 moveDirection = Vector2.zero;

    private void OnEnable()
    {
        playerControl.Enable();
    }
    private void OnDisable()
    {
        playerControl.Disable();
    }

    // Update is called once per frame
    void Update()
    {
        

        moveDirection = playerControl.ReadValue<Vector2>();
    }

    private void FixedUpdate()
    {
        rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
    }
}

到目前為止,這就是我應用於播放器對象的內容。 實際移動時沒有問題,但墜落無法正常工作

在 FixedUpdate 中,您設置 RigidBody 的速度,包括 y 分量。 這與重力相互作用不佳。

重力降低 RigidBody2D 的垂直速度,使物體下落。 同時,您的代碼每幀都會擦除這些更改,這意味着它無法向下加速,從而導致它以非常緩慢且恆定的速度下降(而不是像預期的那樣加速向下)。

如果你可以完全控制你的垂直運動,重力將如何運作? 如果玩家無法控制他們的垂直運動,請將此行更改為:

rb.velocity = new Vector2(moveDirection.x * moveSpeed, rb.velocity.y);

這將解決問題,但會刪除您的垂直控件。 這是你想要的嗎?

如果你想保持垂直運動但不覆蓋重力,你必須做出某種妥協。 如果您希望重力在您不控制角色的垂直運動時起作用,您可以這樣做:

if (moveDirection.y > 0.001)
{
rb.velocity = new Vector2(moveDirection.x * moveSpeed, moveDirection.y * moveSpeed);
}
else
{
rb.velocity = new Vector2(moveDirection.x * moveSpeed, rb.velocity.y);
}

您還可以將垂直運動添加到垂直速度。 這將意味着玩家無法像水平速度那樣完全控制垂直速度,而是能夠對其施加力。

rb.velocity = new Vector2(moveDirection.x * moveSpeed, rb.y + moveDirection.y * verticalMoveSpeed);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM