How to solve double jumping

家住魔仙堡 提交于 2020-11-29 08:32:05

问题


I've followed the Unity tutorial for "Roll-A-Ball", and have added some extensions. The ball can now jump, but it jumps too many times each jump; I just want the ball once at a time when I press on SPACE. Now I can press on SPACE 3 times an it'll jump higher and higher.

  if (Input.GetKeyDown(KeyCode.Space))
        {
            Vector3 jump = new Vector3(0.0f, 150.0f, 0.0f);

            rb.AddForce(jump);
        } 

EDIT:

Have tried changing the code a little bit, but now I can ONLY jump once (the first time)

private void textBox_KeyDown(object sender, KeyEventArgs e)
{
      if (Input.GetKeyDown(KeyCode.Space) && jump.y <= 0.0f)
    {
        jump.Set(0.0f, 150f, 0.0f);
        rb.AddForce(jump);

     }
    }

回答1:


This can get a bit hard to follow (since it's not a step-by-step tutorial, but rather a scheme).

You must check for when the ball reaches the floor checking if the velocity ever gets at 0 or above after the first press. Once it does, then set some bool (here named CanJump) to true (or whatever your language defines for true).

There is some more checking to do as well; once CanJump is set to true (because your velocity is now >= 0), set also an int variable called NumJumps to 0. And increment it each jump. This way you can set CanJump to false after two jumps, which prevents the ball from jumping.

Please note I know nothing about Unity 3D, but I have a bunch of experience with 3D games (like Unreal Engine 1 and thus UT99 modding).




回答2:


I've found a solution. The solution is to add OnCollisionEnter where you can handle what will happen when the player collides with the ground. Furthermore I've added a counter which is set to 0 when the player jumps and 0 again when he collides with the ground.

The counter:

  if (Input.GetKeyDown(KeyCode.Space))
    {
        if (JumpCount < 1)
        {
            Vector3 jump = new Vector3(0.0f, 250.0f, 0.0f);
            rb.AddForce(jump);
            JumpCount++;
        } 
    }

The counter is set to 0 here:

 void OnCollisionEnter(Collision other)
{
    JumpCount = 0;
}



回答3:


I've found that the best solution is to use a Raycast.

bool isOnGround = Physics.Raycast(transform.position, -Vector3.up, 1.875f);

Replace 1.875f with the distance between your character's origin and the ground, plus a little bit extra. Then, you can check for isOnGround when deciding whether a jump should happen or not.



来源:https://stackoverflow.com/questions/39358834/how-to-solve-double-jumping

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