How to bounce a ball in M shape?

I have a flat ground that is not tilted and a 3d sphere ball. The ball is bounced only in Y axis. I want that ball bounce in M shape as shown in uploaded picture.

I tried the following code:

rb2d.velocity = new Vector3(250f, 1f, 0);

and few others searching in the internet. None of them works.

Thanks in advance.110402-m-shape-bounce-ball.png

To create a naturally bouncing object you can either use physics, move it with a script, or define its path with an animation.

The easiest is with physics: you need a SphereCollider on your ball and a Rigidbody, plus a bouncy physics material (bounciness about 0.5). The object on which it will fall should also have a Collider (but no Rigidbody), and mark it static to help the physics system. This should already work, but if you want to make sure that your ball does not roll away, set the Rigidbody constaints for x and z position.

With a script I would use Unity Wiki’s Mathfx.Bounce() function:

[SerializeField] private float bounceHeight = 1.0f;
[SerializeField] private float bounceDuration = 3.0f;

private void Start () {
    StartCoroutine(BounceAnimation());
}

private IEnumerator BounceAnimation () {
    float t = 0;
    Vector3 originalPosition = transform.position;
    while (t < bounceDuration) {
        transform.position = originalPosition + new Vector3(0, bounceHeight * Mathfx.Bounce(t / bounceDuration), 0);
        yield return null;
        t += Time.deltaTime;
    }
    transform.position = originalPosition;
}

Note that I have not used Mathfx.Bounce() this way and this code has not been tested, but it probably only needs a little tweaking to work.

Finally, with an animation you add an Animation component, create an animation clip, and create your custom bounce curve for the transform.position.y component. In my opinion this is the least natural way, but you have a lot of control how the bounce looks exactly.

You can do something like:

float gravity = 0.5f;
Vector3 velocity = new Vector3(250, 5 ,0);
bool isGrounded = true;

public void Update() {
     if(isGrounded)
          velocity.y = 5;
     
     if(velocity.x > gravity)
          velocity = new Vector3(velocity.x-gravity,velocity.y,0);
     
     if(velocity.y > gravity)
          velocity = new Vector3(velocity.x,velocity.y-gravity,0);

     transform.position += velocity;
}

If you want to do it manually