簡體   English   中英

試圖使我的2D角色翻倍-它不起作用,我不知道為什么?

[英]Trying to make my 2D character double jump - it's not working and I don't know why?

我正在制作2D平台游戲。 到目前為止,這是我的代碼。 角色僅在接觸地面時才跳,但兩次跳的代碼不起作用。 任何幫助表示贊賞。 我是腳本新手,我不明白自己做錯了什么?

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PlayerController : MonoBehaviour {

    public float speed = 12f, jumpHeight = 30f;
    Rigidbody2D playerBody;
    Transform playerTrans, tagGround;
    bool isGrounded = false;
    public LayerMask playerMask;
    public float maxJumps = 2;
    public float jumpsLeft = 2;



    // Use this for initialization
    void Start ()
    {
        playerBody = this.GetComponent<Rigidbody2D>();
        playerTrans = this.transform;
        tagGround = GameObject.Find(this.name + "/tag_Ground").transform;

    }

    // Update is called once per frame
    public void FixedUpdate ()
    {
        isGrounded = Physics2D.Linecast(playerTrans.position, tagGround.position, playerMask);
        Move();
        Jump();
        DoubleJump();

    }

    private void Move()
    {
        float move = Input.GetAxisRaw("Horizontal") * speed;
        playerBody.velocity = new Vector2(move, playerBody.velocity.y);
    }

    private void Jump()

    {
        if (isGrounded)
        {


            if (Input.GetButtonDown("Jump"))
            {
                playerBody.velocity = new Vector2(playerBody.velocity.x, jumpHeight);


            }


        }

    }
    private void DoubleJump()
    {
        if (Input.GetButtonDown("Jump") && jumpsLeft > 0)
        {
            Jump();
            jumpsLeft--;
        }

        if (isGrounded)
        {
            jumpsLeft = maxJumps;
        }
    }
}

嘗試用DoubleJump方法的代碼替換您的Jump方法代碼,並在應用跳轉之前刪除對IsGrounded的檢查。 否則,您的角色必須每次都在地面上。 然后,刪除不再需要的DoubleJump方法。 如果您稍后在游戲中將DoubleJump用作附加技能,則隨着玩家獲得技能而增加maxJumps。 最初將其設置為1,這樣它們每次都必須接地。

        private void Jump() {
        if (isGrounded) {
            jumpsLeft = maxJumps;
        }
        if (Input.GetButtonDown("Jump") && jumpsLeft > 0) {
            playerBody.velocity = new Vector2(playerBody.velocity.x, jumpHeight);
            jumpsLeft--;
        }
    }

您的代碼沒有多大意義。 您應該使用一種方法來處理跳躍,並執行以下操作:

private void HandleJump()
{
    if(isGrounded) {
        jumpsLeft = maxJumps;
    }

    if(Input.GetButtonDown("Jump") && jumpsLeft > 0) {
        playerBody.velocity = new Vector2(playerBody.velocity.x, jumpHeight);
        jumpsLeft--;
    }
}

這樣,您可以進行三級跳躍,也可以進行任意多次跳躍。

暫無
暫無

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

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