Unity bouncing ball with the same height and falling speed control

2010 views unity3d
3

how do I create a bouncing ball in unity that bounces to the same height and that I can make it fall quicker or slower? A person told me to use:

heightVector * |sin(time * speed)|

but I don't know where to insert it. I'm really noob at these things. Help!

answered question

1 Answer

10

Your formula is correct.
The heightVector is the maximum height of your ball. For example if it's (0,10), then it means that your ball will go 10 meters high.
The time is simply a timer. The speed is the speed of your ball.

However, I recommend to multiply the speed by Time.deltaTime to make the bounce frame-rate independent.

Let's start writing code.
heightVector and speed have no complexity. Just create two public fields and you're done!

class Bouncer : MonoBehaviour
{
    public float Speed = 10;
    public Vector2 HeightVector = new Vector2(0,10);
}

To create a timer, you need a float variable. Then you need to add Time.deltaTime to it on every Update call.

class Bouncer : MonoBehaviour
{
    public float Speed = 10;
    public Vector2 HeightVector = new Vector2(0,10);

    float timer;
    void Update()
    {
         timer += Time.deltaTime;
    }
}

Congrats! you now have your timer!

Now you are really close to end. You just need calculate the current position of the ball and apply it to its transform.

class Bouncer : MonoBehaviour
{
    public float Speed = 10;
    public Vector3 HeightVector = new Vector3(0,10);

    float timer;
    void Update()
    {
         timer += Time.deltaTime;

         Vector3 currentPosition = HeightVector * Mathf.Abs(timer * Speed * Time.deltaTime);

         transform.position = currentPosition;
    }
}

Now you need to attach the Bouncer script to your ball and your ball should start bouncing!

posted this

Have an answer?

JD

Please login first before posting an answer.