- Home /
how to make 2d character jump?
Hello! I'm currently working on a game as the main animator and character coder. And I have a issue, I currently have the animations and code for the character to move left, right and to be idle. But I am also trying to implement the character to jump, each tutorial I get confused because some things that they type are not working in mine ((guessing it's outdated)) I made the bool for ground and a game object called "GroundCH" I put it at the characters feet but that's as far as I could go without getting completely confused on these tutorials
here's my code for the character to just move around
public float maxSpeed = 8f;
bool left = true;
Animator a;
void Start () {
a = GetComponent<Animator> ();
}
void FixedUpdate () {
float move = Input.GetAxis ("Horizontal");
a.SetFloat ("Speed", Mathf.Abs (move));
GetComponent<Rigidbody2D> ().velocity = new Vector2 (move * maxSpeed, GetComponent<Rigidbody2D> ().velocity.y);
if (Input.GetKey (KeyCode.LeftArrow)) {
transform.position += Vector3.left * maxSpeed * Time.deltaTime;
}
else if (Input.GetKey (KeyCode.RightArrow)) {
transform.position += Vector3.right * maxSpeed * Time.deltaTime;
}
if (move > 0 && left)
Flip ();
else {
if (move < 0 && !left)
Flip ();
}
}
void Flip()
{
left = !left;
Vector3 scale = transform.localScale;
scale.x *= -1;
transform.localScale = scale;
}
}
I dont see any code that will make the character jump here. There is more than one way to make it jump, some more complicated that others. The most simple I can think of is: rb = GetComponent(); float jumpHeight = 5f; if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Space)){ rb.transform.position += new Vector2(rb.transform.position.x, rb.transform.position.y += jumpHeight);
Of course, this will allow the user to keep jumping every time he presses Space, which will be poor gameplay as he can just jump through the sky without worry. $$anonymous$$ost of the time you check if he collides with floor. $$anonymous$$y favourite way in 3d is to use a Raycast from the centre of the sprite, pointing downwards, called IsGrounded and it returns true if the Raycast hits anything. Here is a link, I'm fairly sure it would work in 2d too: https://answers.unity.com/questions/196381/how-do-i-check-if-my-rigidbody-player-is-grounded.html
a more simple way than checking collision with ground would be: if (Input.Get$$anonymous$$eyDown($$anonymous$$eyCode.Space) && rb.velocity.y
Your answer
Follow this Question
Related Questions
Can't make my character to jump ?? 0 Answers
Jump while running not faster than normal jump. Any help with the code? 1 Answer
Shift BHOP in Character Controller 0 Answers
My Character controller keeps jumping infinitely 2 Answers
[SOLVED] 2D Character Controller gains velocity when colliding with a corner 1 Answer