Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to jump in Unity 3d?

can anyone share with me a script that I could use for jumping of the character for this script? I would greatly appreciate it, I'm 12 and just starting, it would help me to finish my project. Thank you in advance.

like image 646
Jobrzut Avatar asked Nov 28 '22 05:11

Jobrzut


1 Answers

I would recommend starting with some of the courses on their website (http://unity3d.com/learn ),but to answer your question the following is a general script that would work.

using UnityEngine;
using System.Collections;

[RequireComponent(typeof(Rigidbody))]
public class PlayerController : MonoBehaviour {
    public Vector3 jump;
    public float jumpForce = 2.0f;

    public bool isGrounded;
    Rigidbody rb;
    void Start(){
        rb = GetComponent<Rigidbody>();
        jump = new Vector3(0.0f, 2.0f, 0.0f);
    }

    void OnCollisionStay(){
        isGrounded = true;
    }

    void Update(){
        if(Input.GetKeyDown(KeyCode.Space) && isGrounded){

            rb.AddForce(jump * jumpForce, ForceMode.Impulse);
            isGrounded = false;
        }
    }
}

Lets break that down a bit:

[RequireComponent(typeof(Rigidbody))] 

Want to make sure you have a rigidbody first before we make any calculations.

public Vector3 jump; 

Vector3 is a variable storing three axis values. Here we use it to determine where we're jumping.

public bool isGrounded; 

We need to determine if they're on the ground. Bool (or boolean) for yes we are (true), or no we are not (false).

void OnCollisionStay(){
    isGrounded = true;
}

in Start(), we assign the variable rb (set from Rigidbody rb) to the component attached to your GameObj and also we assign values to the Vector3 jump.

Then we Update() with this:

if(Input.GetKeyDown(KeyCode.Space) && isGrounded){     
    rb.AddForce(jump * jumpForce, ForceMode.Impulse);
    isGrounded = false;
}

means that if the player hits the Space button and at the same time, the GameObj is grounded, it will add a physic force to the rigidbody, using.

AddForce(Vector3 force, ForceMode mode)

where force is the Vector3 storing the movement info and mode is how the force will be applied (mode can be ForceMode.Force, ForceMode.Acceleration, ForceMode.Impulse or ForceMode.VelocityChange, see ForceMode for more).

Lastly, google is your best friend. Be sure exhaust your options in the future in order to get the fastest results!

Answer is a simplified rewrite of this: https://answers.unity.com/questions/1020197/can-someone-help-me-make-a-simple-jump-script.html

like image 187
Treasure Dev Avatar answered Nov 30 '22 19:11

Treasure Dev