- Home /
How do I define the speed of my player in the y axis?
I'm a real beginner but having great fun so far (=
What I want to do is be able to play around with- "if" statements to tell unity when my player can jump or not.
How do I define his speed in the y axis?
For example i'd like to do this:
if (speedY == 0 && Input.GetButton("Jump")) { jump; }
So basically only if he is standing still on the ground he could jump.
Thanks a lot in advance!
is this question closed? did I help? if so mark as correct please.
Answer by CrazyKane · Jan 09, 2014 at 02:22 AM
var notAirbourne = true;
var jump: KeyCode;
var jumpAmount: float = 12;
var jumpRate: float = 1.2;
private var nextJump = 0.0;
if(Input.GetKey(moveRight) && Input.GetKey(jump) && Time.time > nextJump && notAirbourne == true){
notAirbourne = false;
nextJump = Time.time + jumpRate;
rigidbody2D.velocity.x = moveSpeed;
rigidbody2D.velocity.y = jumpAmount;
}
if(Input.GetKey(moveLeft) && Input.GetKey(jump) && Time.time > nextJump && notAirbourne == true){
notAirbourne = false;
nextJump = Time.time + jumpRate;
rigidbody2D.velocity.x = moveSpeed * -1;
rigidbody2D.velocity.y = jumpAmount;
}
This is for 2d, if you add a tag to objects that are the ground they have to collide with them to be able to jump again.
if (coll.gameObject.tag == "Ground"){
notAirbourne = true;
}
Answer by OP_toss · Dec 21, 2013 at 12:42 AM
You could manually check the speed of the player by storing the previous position from the last frame (speed = (currentPos - prevPos)/Time.deltaTime). But I don't think this is the best test for jumping.
What if you were walking up a slope? Now suddenly, you can't jump while walking upwards, or downwards for that matter.
Rather, I suggest you have a bool, or better yet, a state variable that you set when you begin a jump, and revert when you end a jump. Then you can check against the state to see if they can or cannot jump. States can be as simple as an enum, or you can build a state machine if you want to get fancy. But they are the best way to do this type of thing, and will make future complexity much nicer to deal with.
For instance, what if you want to allow double jumps? Simply add a state for JUMPING, and another for DOUBLEJUMPING, and check that the state is either WALKING, STANDING, or JUMPING in order to permit a jump. EZ!
Hope this helped!