簡體   English   中英

當我希望我的玩家跳躍時,他正在飛行(Unity2d)

[英]When I want my Player to jump he is flying (Unity2d)

您好,我想制作我的第一個 2D 游戲,但是當我想跳躍時,我的 Player 正在飛行並且他沒有回到地面。 我不知道為什么它不起作用。 希望有人可以幫助我。 謝謝你。 這是我的代碼:

using UnityEngine;
using System.Collections;
public class Move2D : MonoBehaviour
{
    public float speed = 5f;
    public float jumpSpeed = 8f;
    private float movement = 0f;
    private Rigidbody2D rigidBody;
    // Use this for initialization
    void Start()
    {
        rigidBody = GetComponent<Rigidbody2D>();
    }

    // Update is called once per frame
    void Update()
    {
        movement = Input.GetAxis("Horizontal");
        if (movement > 0f)
        {
            rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);
        }
        else if (movement < 0f)
        {
            rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);
        }
        else
        {
            rigidBody.velocity = new Vector2(0, rigidBody.velocity.y);
        }
        if (Input.GetButtonDown("Jump"))
        {
            rigidBody.velocity = new Vector2(rigidBody.velocity.x, jumpSpeed);
        }
    }
}

您在跳躍時設置了 y 速度,但從不將其設置回其他任何值。 我建議你使用rigidBody.AddForce進行跳躍:

rigidBody.AddForce(transform.up * jumpSpeed, ForceMode2D.Impulse);

我還不得不說,您的第一個 if..else if...else 似乎是多余的。

如果運動> 0,你做X,運動是< 0,你做的完全一樣,如果運動== 0,即使你寫得不同,你仍然做同樣的事情。 (如果運動 == 0 則運動 * 速度也是 0)。 所以你可以只是 state

rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);

根本不使用 if 。

編輯:我不小心寫錯了要使用的行,現在修復它。

編輯2:因此,在這兩項更改之后,您的更新 function 將如下所示:

void Update()
{
    movement = Input.GetAxis("Horizontal");
    rigidBody.velocity = new Vector2(movement * speed, rigidBody.velocity.y);

    if (Input.GetButtonDown("Jump"))
    {
        rigidBody.AddForce(transform.up * jumpSpeed, ForceMode2D.Impulse);
    }
}

暫無
暫無

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

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