繁体   English   中英

如何使用 Input.GetButton() 而不一次获得多次跳跃? unity 2D 字符 Controller C#

[英]How do I use Input.GetButton() without getting several jumps at once? Unity 2D Character Controller C#

我已经制作了很多 2D 游戏,你是屏幕上的一个东西,然后你跳来跳去等等,但是在我最新的项目中,三角形运行(几何冲刺,但更糟),我希望能够按住鼠标和角色你知道,以均匀的速度跳跃,就像在几何冲刺中一样,所以我没有使用Input.GetButtonDown ,而是将其替换为Input.GetButton ,然后我放了一个return; if语句之后,因此每个Update()只能运行一个if (即它所在的 function),但这使得除了最快的点击之外,任何东西都可以将播放器启动到正常跳跃高度的 10-20 倍。 我尝试了很多不同的方法来确保if语句在每个Update()中只运行一次,这让角色控制器有足够的时间来检查玩家是否接地以允许或阻止跳跃,所以我不知道为什么它让我兴奋起来。 编辑:使用Input.GetButtonDown一切正常。

到目前为止,这是玩家运动的全部代码,我刚刚开始游戏,所以还没有太多代码:

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

public class PlayerMovement : MonoBehaviour
{

    public CharacterController2D controller;
    bool jump = false;
    public Rigidbody2D rb;
    public float moveSpeed = 10f;
    public Transform transform;
    private float moveY = 0f;
    private int jumpCounter = 0;
    private bool jumpIf = true;


    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetButton("Jump") && jumpIf) // if we press the jump button
        {
            jump = true; // set jump bool to true (see void fixedupdate for more)
            jumpIf = false;
        }
        else
        {
            jump = false;
        }
        jumpIf = true;
        return;
    }

    void FixedUpdate() // called a set amount of times per second, used with physics movement etc lol
    {

        controller.Move(0f, false, jump); // move in which direction, are we crouching, are we jumping
        jump = false;
        moveY = rb.velocity.y;
        rb.velocity = new Vector2(moveSpeed, moveY);
    }
}


如您所见,在if中,它非常混乱,因为我最终尝试了各种事情。

非常感谢!

您是否尝试在带有 if 语句的FixedUpdate中使用GetButtonUp 我在Update中的交互有类似的问题。 Update上使用GetButton将使游戏在您开始按下跳转键后每帧都执行跳转,而使用GetButtonUp则只有在松开跳转键时才会执行操作。 像这样的东西可能会起作用:

void FixedUpdate()
{
        if (Input.GetButtonUp("Jump")) // if we press the jump button
            {
                jump = true; // set jump bool to true, in case you want to use it for an animation,etc.
               //Jump code here.
                controller.Move(0f, false, jump);
                moveY = rb.velocity.y;
                rb.velocity = new Vector2(moveSpeed, moveY);
            }
}

或者在Update中使用CoRoutineyield return new WaitForSeconds()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM