Search code examples
c#unity-game-enginegameobject

how to make gameobject jump forward?


hi i'm really new to this and would like some help, i would like to know how i can make my game object jump forward (the longer you hold the further it'll jump), i have a rigid body on my game object already in case that helps.

public class PlayerScript : MonoBehaviour {

public float speed;

private Vector3 dir;

// Use this for initialization
void Start () 
{
    dir = Vector3.zero;
}

// Update is called once per frame
void Update () 
{
    if (Input.GetMouseButtonDown(0)) 
    {
        if (dir == Vector3.forward)
        {
            dir = Vector3.right;
        }
        else 
        {
            dir = Vector3.forward;
        }

    }

    float AmToMove = speed * Time.deltaTime;
    transform.Translate (dir * AmToMove);
}

so far i only managed to make it move forward and right but instead i would like it to jump forward and jump right.


Solution

  • public float thrust;
            public Rigidbody rb;
            void Start() {
                rb = GetComponent<Rigidbody>();
            }
            void FixedUpdate() {
                rb.AddForce(transform.up * thrust);
            }
    //This will add a force to the rigidbody upwards. 
    

    If you want to use the rigidbody for movement you should apply a force to it. Right now you are simply moving the world transform of the object.