Item Bounce in a Top-Down 2D Game?

Hi all,

I am creating a topdown 2D and want items to have a nice little bounce when they spawn in. I found this article here that basically has the exact effect I want: Top-down bouncing loot effects. HOWEVER, this article is for Gamemaker and not for Unity.

I tried recreating his code as 1:1 as possible (Obviously making changes for Unity), but really could not get the desired effect. Instead, I more tried to apply the same concepts as in the article instead of trying to copy the code exactly. Here is what I came up with:

public class ItemDropScript : MonoBehaviour
{
    float floorY;
    Rigidbody2D rb;

    public int bounces = 5;

    public float speed = 10.0f;

    void Start()
    {
        rb = this.gameObject.GetComponent<Rigidbody2D>();
        floorY = this.gameObject.transform.position.y;
        this.gameObject.transform.position = new Vector3(this.gameObject.transform.position.x, floorY + 1, this.gameObject.transform.position.z);


    }

    // Update is called once per frame
    void FixedUpdate()
    {

        if ((bounces > 0) && (this.gameObject.transform.position.y > floorY) && (speed > 0))
        {
            transform.Translate(Vector2.down * Time.deltaTime * speed);
        }
        else if (bounces > 0)
        {
            transform.Translate(Vector2.up * bounces * Time.deltaTime * speed);
            bounces--;
            speed = (float)(speed * 0.6 - 0.7);
            print("bounces:" + bounces);
        }
        else
        {
            speed = 0;
        }
       
    }
}

This code sort of gets the same effect, but is not nearly as smooth and appealing as the effect in the article. How can I go about recreating the bouncing effect in this article in Unity2D? I’m not attached to what I have now and am willing to completely re-write if needed.

You might consider using DOTween, there’s a free version. Its handy for stuff like this.

I am also a GM developer on the side. That article is often referenced when you’re trying to introduce yourself with tweening in general. However it’s not really practical to write the thing from scratch as there are already tons of premade libraries that can do that, and even offers a lot more customization, such as multiple tween modes, acceleration curves, etc.

You may also want to check the source code in question and open it with GM. I think you misplaced some lines onto the wrong events, as GML is basically pseudo-code, there’s hardly any language specific features there - it’s almost like reading a raw inanimate algorithm.

maybe you should post a video of what you have currently so we can see by how far off you are

Don’t write code for things that can simply be animations.

And if you must write code (eg, dynamic behaviour), then as Vonchor points out, use a tweening package.

More:

https://www.youtube.com/watch?v=Fy0aCDmgnxg