I am a beginner in game development. Currently I am making a 2d platformer game in unity engine. I am unable to make my player jump. So please can you provide me a code for making my player jump.
CodePudding user response:
You can do it in different ways :
either by using a Rigidbody and add force to it like this :
_yourRigidbody = GetComponent<Rigidbody>();
_jumpForce = 10;
private void MakePlayerJump()
{
Vector2 jumpVector = new Vector2(0,_jumpForce);
_yourRigidbody.AddForce(jumpVector);
}
or by creating a 2d controller physic system based on the player's position which is way more complex if you're starting Unity, but if you want to do this here's a great 2D plateformer controller you can take example of : https://www.youtube.com/watch?v=3sWTzMsmdx8
CodePudding user response:
public float speed = 10f;
public float jumpForce = 5f;
private Rigidbody2D rb;
void Start()
{
rb = gameObject.GetComponent<Rigidbody2D>();
}
// Update is called once per frame
void Update()
{
if (Input.GetButtonDown("Jump"))
{
rb.AddForce(new Vector2(0f, jumpForce), ForceMode2D.Impulse);
}
Vector3 movement = new Vector3(Input.GetAxis("Horizontal"), 0f, 0f);
transform.position = movement * Time.deltaTime * speed;
}
The code above should allow for basic movement and jumping, however this code does allow for the user to jump mid air, as there is no ground check I'm not sure if you want that or not. It will also require a rigidbody component to be attached to the gameObject.