简体   繁体   中英

Jumping Is Not Working As Expected Unity 3D

Hello I am trying to figure out why my jumping is inconsistent. I've looked at many StackOverflow questions and I still can't find a solution. If someone could help that would be amazing! :D

using UnityEngine;
using System.Collections;

public class BallMovement : MonoBehaviour {

public float speed;

private Rigidbody rb;

void Start ()
{
    rb = GetComponent<Rigidbody>();
}

void FixedUpdate ()
{
    Camera mainCamera = GameObject.FindGameObjectWithTag("8BallCamera").GetComponent<Camera>() as Camera;
    float moveHorizontal = Input.GetAxisRaw ("Horizontal");
    float moveVertical = Input.GetAxisRaw("Vertical");
    Vector3 movement = mainCamera.transform.forward * moveVertical * 30;
    rb.AddForce (movement * speed);

    if (Input.GetKeyDown("space")) {
        rb.AddForce(0,2f,0, ForceMode.Impulse);
    }
}

}

When asking a question, try to be more detailed on the facts of the issue, as phrases like "not working as expected" and "jumping is inconsistent" is pretty subjective, and could mean something different depending who reads it :)

I tried out the code on my machine, and found that sometimes pressing the space bar would not initiate the jump. No other issues seemed to arise (although you may want to place in a cooldown for your jump later on).

The issue was with your jump codes being in FixedUpdate() . FixedUpdate() seems to run before Update() , but it's not always called. This is why the space input was sometimes unnoticed.

Placing it inside Update() will fix the issue.

using UnityEngine;
using System.Collections;

public class BallMovement : MonoBehaviour
{

    public float speed;
    private Rigidbody rb;

    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    private void Update()
    {
        Camera mainCamera = GameObject.FindGameObjectWithTag("8BallCamera").GetComponent<Camera>() as Camera;
        float moveHorizontal = Input.GetAxisRaw("Horizontal");
        float moveVertical = Input.GetAxisRaw("Vertical");
        Vector3 movement = mainCamera.transform.forward * moveVertical * 30;
        rb.AddForce(movement * speed);

        if (Input.GetKeyDown("space"))
        {
            rb.AddForce(0, 2f, 0, ForceMode.Impulse);
        }
    }
}

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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