- Home /
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.
Answer by FourSheds · Jun 26, 2011 at 06:41 AM
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.
Note also that FourSheds used GetButtonDown(), not GetButton(). GetButton() will trigger every single frame that the jump button is pressed, but GetButtonDown() will only trigger once when the button is pressed. It has to be release and pressed again to trigger a second time.
Answer by Bunny83 · Jun 26, 2011 at 03:18 AM
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()`
How exactly would I go abou doing that? I mean, I'm really not very good at scripting. ( I'm only 13 years old)
Exactly as you have used Translate, and as the linked documentation shows.
Answer by hypnoslave · Jun 26, 2011 at 05:33 AM
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.
Your answer
Follow this Question
Related Questions
2D (With Planes) Jump Script 0 Answers
Rigidbody2d not falling once in the air 1 Answer
how the ball bounces of equal in angles? 1 Answer