- Home /
Jump of 2d character is sometimes stronger.
Hey Community,
I have a problem setting up a 2D character. When I play it in the Editor my character works fine, but sometimes the character is jumping a lot higher then it should. Can somebody help me? Here is my code: (Yes, I want that the character is moving itself, without Input)
using UnityEngine;
using System.Collections;
public class player : MonoBehaviour {
public float speed;
public float jumpforce;
bool isgrounded;
// Update is called once per frame
void Update () {
//Constant Force
if (isgrounded) {
rigidbody2D.AddForce (new Vector2 (speed, 0));
rigidbody2D.velocity = Vector2.ClampMagnitude (rigidbody2D.velocity, speed);
}
//Jump
if (Input.GetKeyDown (KeyCode.Space) && isgrounded) {
rigidbody2D.AddForce(new Vector2(0, jumpforce));
}
//reset
if(Input.GetKeyDown("r"))
Application.LoadLevel(0);
}
// check collision and update isgrounded
void OnCollisionStay2D(Collision2D col)
{
isgrounded = true;
}
void OnCollisionExit2D(Collision2D col)
{
isgrounded = false;
}
}
Thanks for every answer and excuse my bad english ;)
Julian
Comment
Answer by blueteak · Dec 06, 2014 at 07:28 PM
First, set isGrounded false when jump is pushed, it may get called twice.
//Jump
if (Input.GetKeyDown (KeyCode.Space) && isgrounded) {
rigidbody2D.AddForce(new Vector2(0, jumpforce));
isgrounded = false;
}
Second, why not use
rigidbody2D.velocity = new Vector3(rigidbody2D.velocity.x, JumpForce, rigidbody2D.velocity.z);
That way you aren't adding force, you're just setting the velocity.