How to jump in Unity 3d?

守給你的承諾、 提交于 2020-08-17 11:59:06

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/58377170/how-to-jump-in-unity-3d

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