[英]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
中使用CoRoutine并yield return new WaitForSeconds()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.