Home > Software engineering >  How to make jump system in unity?
How to make jump system in unity?

Time:05-16

Here is my code for moving around in Uunity, however I can't seem to make the character jump. The moving camera and collect item on collision has also been implemented, now I just need to find out how to jump?

Why is it asking me for more details?

using TMPro;
using UnityEngine;
using UnityEngine.InputSystem;

public class DemoComponent : MonoBehaviour
{
    private Vector3 vectorToMove = new(1f, 0.5f, 1.5f);
    private Vector3 movementInput = Vector3.zero;

    private readonly float moveSpeed = 0.2f;
    private readonly float rotationSpeed = 0.05f;
    private readonly Vector3 rotationInput = Vector3.zero;
    public TextMeshProUGUI displayText;

    // Update is called once per frame
    private void Update()
    {
        var movementVector = transform.forward;
        movementVector *= movementInput.y;
        movementVector  = transform.right * movementInput.x;

        //transform.position  = movementVector * moveSpeed;
        GetComponent<Rigidbody>().MovePosition(transform.position   movementVector * moveSpeed);
        transform.rotation = Quaternion.Euler(transform.rotation.eulerAngles   rotationInput * rotationSpeed);
    }

    private void OnMove(InputValue value)
    {
        //Debug.Log(value.Get<Vector2>());
        movementInput = value.Get<Vector2>();
    }
}

CodePudding user response:

First you need to save the rigidbody instance to increase performance as well as access it:

private Rigidbody rb; // define rigidbody holder

private void Start()
{
    rb = GetComponent<Rigidbody>(); save instance on rb
}

This code is a simple jump with adjustable power. In most cases with `mass = 1`, a `jumpPower` of 300 is sufficient.
public float jumpPower = 300f;
private void Jump(float jumpPower) => rb.AddForce(Vector3.up * jumpPower);

Finally, by pressing the Space key, the jump method is executed.

private void Update()
{ 
    // some codes....

    if (Input.GetKeyDown(KeyCode.Space)) Jump(jumpPower);
}

CodePudding user response:

The jump is written entirely in accordance with the idea of ​​moving in the direction, and it is found that the object moves to the control in an instant.

    void Update() {
        if (Input.GetKeyDown(KeyCode.Space)) {
       // If you don't add Space.World, if the object rotates, the direction of the jump is not up, it is inclined
        transform.Translate(new Vector3(0, 10, 0), Space.World);
       }
    }

If using MovePosition

void Update() {
    if (Input.GetKeyDown(KeyCode.Space)) {
 
        var component = transform.GetComponent<Rigidbody2D>();
        component.MovePosition(component.position   new Vector2(0, 5));
    }
}

Slow ascent, highly available controls, a bit more code

  private float speed = 30;
  bool jump = false;
  float jhigh = 0f;
  float maxJhigh = 5f;
 
  void Update() {
 
    if (Input.GetKeyDown(KeyCode.Space)) {
        jump = true;
        print("start");
        jhigh = 0;
    }
    
    if (jump) {
        float high = 1 * speed * Time.deltaTime;
 
        if (jhigh   high >= maxJhigh) {
            jump = false;
        }
        transform.Translate(new Vector3(0, high, 0), Space.World);
        jhigh  = high;
        print(jhigh);
    }
  }

Use Force to apply force, there is a sense of bouncing, this is recommended

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

        var component = transform.GetComponent<Rigidbody2D>();
        component.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
    }
}

Added ray detection, you can only jump on the ground

//for output on the screen
private void OnDrawGizmos() {
    Gizmos.color = Color.white;
    Gizmos.DrawRay(transform.position   colliderOffset,Vector3.left);
}

void Update() {
    
    RaycastHit2D onGround2 = Physics2D.Raycast(transform.position   colliderOffset, -Vector2.up);
    print("b"   transform.position   ",c="   colliderOffset   ",d="   onGround2.distance);
    
    if (onGround2.distance <= 0) {
        if (Input.GetKeyDown(KeyCode.Space)) {
            var component = transform.GetComponent<Rigidbody2D>();
            component.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
        }
    }
}

The problem with the last version is that it may not be on the ground, but it needs to be filtered on other hidden colliders

    Debug.DrawRay(transform.position   colliderOffset, Vector3.down * 5);
    if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.W)) {
        RaycastHit2D onGround2 = Physics2D.Raycast(transform.position   colliderOffset, -Vector2.up, 5, buildingsMask);
        if (onGround2.collider != null && onGround2.distance <= 0) {
            component.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
        }
    }

second stage jump

/**
 * whether to skip once
 */
private bool jumpOne;

void jump() {

    Debug.DrawRay(transform.position   colliderOffset, Vector3.down * 5);
    if (Input.GetKeyDown(KeyCode.Space) || Input.GetKeyDown(KeyCode.W)) {
        RaycastHit2D onGround2 = Physics2D.Raycast(transform.position   colliderOffset, -Vector2.up, 5, buildingsMask);

        if (onGround2.collider != null && onGround2.distance <= 0) {
            rig.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
            jumpOne = true;
        }
        else if (jumpOne) {
            // second jump
            rig.AddForce(new Vector2(0, 10), ForceMode2D.Impulse);
            jumpOne = false;
        }
    }
}

Thank you hope it can help you

  • Related