Sphere Goes Crazy

I have a ball that has a sphere collider and a rigidbody in my scene.

Here’s my script for the ball:

var jumpSpeed : float = 8.0;


function Update()

{

 if (Input.GetButton ("Jump"))
	 
{
transform.Translate (Vector3.up * Time.deltaTime * jumpSpeed);
}

}

When I press play, everything appears to be fine, but when I press space to jump, the ball goes all over the place and goes backwards and crazy!

I do not want to use a character controller, by the way. I want my ball to be bouncy and for that I need a Physic Material unless someone can think of some way to put a physic material on a character controller.

Also, my game is a 2d game.

Thanks in advance,

Elijah.

Hi Elijah,

Coincidentally, I’m teaching my 13 y.o. son Unity, so complete respect if you’re learning this on your own!

To get the ball to jump via Physics, you could start with the following:

var jumpForce : float = 8.0;
function Update () {
	
	if (Input.GetButtonDown ("Jump"))
	{
		rigidbody.AddForce(Vector3.up * jumpSpeed);
	}
}

If you’ve used the default values for a sphere and rigidbody, you’ll probably find you need to make jumpForce quite large. This is because you’re only adding a single impulse of force at one moment. For a ball, this may be what you want, but otherwise you can add the same force inside FixedUpdate() over several frames (e.g. by making a timer).

You’ll also notice that the ball can jump many times by pressing the “Jump” key quickly, even when it’s in the air. You could prevent this either by testing for its transform.position.y value, or by limiting how often the “Jump” key can be pressed with a timer.

transform.Translate will actually bypass the physics. You have to use forces to move the rigidbody. The rigidbody have its own velocity property that gets affected by the forces.

Try something like rigidbody.AddForce()

change Input.GetButton to Input.GetButtonDown.

Input.GetButton will return true for every frame that the space bar is held down. if you want to just do a quick jump, change to GetButtonDown – that will only return true on the frame that you actually pressed spacebar.