- Home /
Jumping while moving
Hi I'm fairly new to writing script with Unity. I'm trying to get a ball to jump more than once without stopping. The ball will jump just fine while moving left or right but has to stop before it can jump again. Can anybody suggest how I can fix this problem?
#pragma strict
var Jump : KeyCode;
var stop : KeyCode;
var moveLeft : KeyCode;
var moveRight : KeyCode;
var speed : float = 1;
var jumpHeight : float = 250;
var grounded = false;
function Update ()
{
if (Input.GetKey(moveLeft))
{
GetComponent.<Rigidbody2D>().velocity.x = speed * -1;
if (Input.GetKey(Jump))
{
jump();
}
}
else if (Input.GetKey(moveRight))
{
GetComponent.<Rigidbody2D>().velocity.x = speed;
if (Input.GetKey(Jump))
{
jump();
}
}
else if (Input.GetKey(stop))
{
grounded = true;
GetComponent.<Rigidbody2D>().velocity.y = 0;
}
else if (Input.GetKey(Jump))
{
jump();
}
else
{
grounded = true;
GetComponent.<Rigidbody2D>().velocity.x = 0;
}
}
function OnCollisionEnter(hit : Collision)
{
grounded = true;
}
function jump()
{
if (grounded == true)
{
GetComponent.<Rigidbody2D>().AddForce(Vector3.up * jumpHeight);
grounded = false;
}
}
Cool thanks a lot. Now the only problem I have is when I hold down the jump button down the ball floats upwards...
To do this simply replace Get$$anonymous$$ey with Get$$anonymous$$eyDown
$$anonymous$$ake sure to mark you question as answered ^^
Answer by ForeignGod · Mar 10, 2015 at 01:54 PM
var RSpeed = GetComponent.<Rigidbody2D>().velocity.y;
function Update ()
{
if (RSpeed == 0)
{
grounded = true;
}
}
Adding this to the script should check if you have any velocity on the Y axis, if the velocity is 0 grounded is true. This might fix why grounded wont become true when you keep on moving. I haven't tested this so there might be errors.
EDIT: I tested the script and if i walk left/, jump and land, grounded is true. This should fix your problem ^^