Answer the question
In order to leave comments, you need to log in
Unity, 2D: how to make a jump?
In short, I'm making a 2D game in Unity.
It should be that the player cannot "fly" in the air when pressing "up", but can only jump once. Of course, when I release the "up" key, the player falls sharply. Rigidbody2D hangs on the player ... And so I'm breaking my head, and that's it - I don't understand where the jamb is. The code:
using UnityEngine;
public class PlayController : MonoBehaviour
{
public Vector2 speed = new Vector2(50, 50);
private Vector2 movement;
Rigidbody2D rigidbody2D;
public Vector2 jumpHeight;
void Awake()
{
rigidbody2D = GetComponent<Rigidbody2D>();
GetComponent<Rigidbody2D>().AddForce(jumpHeight, ForceMode2D.Impulse);
}
void Update ()
{
float inputX = Input.GetAxis("Horizontal");
float inputY = Input.GetAxis("Vertical");
movement = new Vector2
(speed.x * inputX,
speed.y * inputY);
}
void FixedUpdate()
{
rigidbody2D.velocity = movement;
}
}
Answer the question
In order to leave comments, you need to log in
What you need to make everything work:
1) Copy the code.
2) The object on which the
Rigidbody hangs must have this script and a collider (required 2d, not a trigger
)
input, you must remember the fact that the jump key was entered and ignore it until landing (the OnCollisionEnter2D method was used for this)
Proceeding from this, complete your example as you like.
public class PlayerController : MonoBehaviour
{
Rigidbody2D m_Rigidbody;
readonly Vector2 force = new Vector2(50, 50);
bool inAir;
private void Start()
{
m_Rigidbody = GetComponent<Rigidbody2D>();
}
void Update()
{
if (Input.GetKey(KeyCode.Space) && !inAir)
{
inAir = true;
m_Rigidbody.AddForce(force);
}
}
private void OnCollisionEnter2D(Collision2D collision)
{
if (collision.gameObject.layer == LayerMask.NameToLayer("Ground"))
inAir = false;
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question