- Home /
Help with making ball jump
Hi guys im really new to Unity, spent the last few days trying to figure out how to make my ball jump using rigidbody. Sort of got it working, however it doesnt seem to fire the code everytime i press the space, there sometimes i have to press it 2-10 times to get the ball to jump. I spend ages crawling through posts and examples but nothing seems to work..below is my script. Thanks for your time.
var speed = 20.0;
var gravitypull = 0;
var jumpSpeed = 5.0f;
//function FixedUpdate() {
function Update(){
if (Input.GetKey ("space") && Physics.Raycast(transform.position, -transform.up,1))
{
rigidbody.velocity.y = jumpSpeed;
//rigidbody.AddForce(Vector3.up * jumpSpeed, ForceMode.Impulse);
}
if (Input.GetKey ("right"))
rigidbody.AddForce(Vector3.right * speed * Time.deltaTime);
}
if (Input.GetKey ("left")) {
rigidbody.AddForce(Vector3.right * -speed * Time.deltaTime);
}
}
I'm just a beginner, but did you try taking out the part that says:
&& Physics.Raycast(transform.position, -transform.up,1
to see if the problem is there? Does "-transform.up" work? How big is the ball? Is one meter enough?
Answer by FLASHDENMARK · Jun 27, 2012 at 08:31 PM
As you are using a rigidbody and you use AddForce I suspect that your ball rotates. And you are using -transform.up in your raycast parameter which is relative to the rotation of the ball.
You should properly use -Vector3.up, like so:
var speed = 20.0;
var gravitypull = 0;
var jumpSpeed = 5.0f;
function Update(){
if (Input.GetKey("space") && Physics.Raycast(transform.position, -Vector3.up, 1))
{
rigidbody.velocity.y = jumpSpeed;
//rigidbody.AddForce(Vector3.up * jumpSpeed, ForceMode.Impulse);
}
if (Input.GetKey ("right")){
rigidbody.AddForce(Vector3.right * speed * Time.deltaTime);
}
if (Input.GetKey ("left")){
rigidbody.AddForce(Vector3.right * -speed * Time.deltaTime);
}
}
Answer by slayer29179 · Jun 27, 2012 at 08:12 PM
To make objects jump I don't usually use raycast, I usually just use;
var jumpSpeed : float = 8.0;
var gravity : float = 20.0;
var rotateSpeed : float = 3.0;
private var moveDirection : Vector3 = Vector3.zero;
function Update()
{
if (Input.GetButton ("Jump"))
{
moveDirection.y = jumpSpeed;
}
// Apply gravity
moveDirection.y -= gravity * Time.deltaTime;
// Move the controller
controller.Move(moveDirection * Time.deltaTime);
}
Maybe you could just add this on the end? otherwise I don't know
This requires a CharacterController. That doesn't sound like the ideal choice for the task the OP faces.
But whatever floats the OP's boat, I guess.
Answer by Eks-Squared · May 07, 2014 at 06:28 AM
I just had this SAME PROBLEM. I did what OrangeLightning suggested and used Update() for button commands instead of FixedUpdate().