How to make a character jumping with just one jump at a time in Unity 3D?

别等时光非礼了梦想. 提交于 2021-02-11 16:48:11

问题


I created a script to make my character jump but it keeps jumping when I keep pressing the button. I just want it to jump once a time.

using UnityEngine;
[RequireComponent(typeof(Rigidbody))]

public class Jump : MonoBehaviour {
   Rigidbody rb;
   void Start()
   {
       rb = GetComponent<Rigidbody>();  
   }
   void Update()
   {
      if (Input.GetKeyDown(KeyCode.Space))
      {
         rb.AddForce(new Vector3(0, 5, 0), ForceMode.Impulse);
      }
   }
}

回答1:


add a state or flag the store the jumping state, when begin to jump, set it to be true.in update method, check the flag before adding force. change the flag to be false after cold down time




回答2:


Keep a Boolean like "canJump" and set it to false when the player jumps. But, rather than a timer as someone already suggested, usually you would use a Physics.Raycast pointing down from the player or some other collision detection to determine when the player has hit the ground, and set canJump to true when that happens. If you use a number for canJump rather than a bool, you can allow double jumps.




回答3:


I would recommand a method that returns a boolean and is checking if your character is grounded. Such an Method is implemented in the unity integrated character controller. Implementing it on your own could look like this:

function IsGrounded(): boolean {
    return Physics.Raycast(transform.position, Vector3.down, collider.bounds.extents.y + offset);
}

you should add a small offset in case the ground is uneven. If you are using a capsule collider on your character you might want to use a capsule check.

function IsGrounded(): boolean {
    return Physics.CheckCapsule(collider.bounds.center,new Vector3(collider.bounds.center.x,
                                collider.bounds.min.y-offset,collider.bounds.center.z),radius);
}

in this case radius should be the radius of your capsule collider and offset a small value you add.




回答4:


To add, create vectors, colliders, and boolean

private BoxCollider2D box;
Vector3 max = box.bounds.max;
Vector3 minValue = box.bounds.minValue;

Vector2 x = new Vector2(max.x, minValue.y -0.1f);
Vector2 y = new Vector2(minValue.x, minValue.y - 0.1f;

Collider2D ground = Physics2D.OverlapArea(x,y);
bool jump = (ground != null) ? true : false;
if (jump && Input.GetKeyDown(KeyCode.Space)) {
    //jump
}

Just add Vectors to check where player is located and a Collider to check if player is on ground, and the bool that determines if jumping is allowed, and put the bool in with Input.GetKeyDown. If bool is true and key is pressed, then jump.



来源:https://stackoverflow.com/questions/60105978/how-to-make-a-character-jumping-with-just-one-jump-at-a-time-in-unity-3d

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!