- Home /
How do I scale a 2D sprite over time?
Hey all!
I'm having a hard time scaling a sprite smoothly.
I've tried a few different ways but I it keeps scaling instantly.
Here's what I have:
void Update ()
{
ballSize = this.gameObject.transform.localScale;
//enemyBallSize = enemyBall.transform.localScale;
DestroyBall ();
scaleSpeed = Time.deltaTime * 30;
}
void OnCollisionEnter2D(Collision2D coll) {
enemyScale = coll.gameObject.transform.localScale.x;
if (coll.gameObject.transform.localScale.x < ballSize.y)
{
currentSize = this.transform.localScale.x;
this.transform.localScale = (new Vector2(currentSize, currentSize) + new Vector2(scale * scaleSpeed, scale * scaleSpeed));
}
Right now, when there is a collision, the ball increases in size but it's instant. I want to be able to have it increase over like 1 second or something, and if possible I would like to have the ball increase past the size it's meant to reach, before scaling down to it's new size, like a bounce affect.
Thanks a lot!
Answer by GiyomuGames · Aug 27, 2015 at 04:58 AM
You can write a coroutine which increases the size of the ball during 1 second (a while(true) loop inside which you increase the size and then wait for a very short amount of time).
You can also set a boolean to true during all the time you want the ball to increase and then increase the scale in the update method.
You can save the Time.time your collision happens and then in the update method increase the scale until the actual time is superior to the time of the collision + whatever time you want.
You can use an animation which does exactly what you want, and trigger it on collision. This is probably the easiest and best way to do it.
Thanks for the pointers, first time I check into animation...had no idea I could play with scale like that! Definitely will be using the animation method!
Answer by OscarScorp · Mar 31, 2019 at 12:36 AM
I found this as the easiest way for me:
float scale = 0.01f;
void Update()
{
scale += 0.05f;
transform.localScale = new Vector2(scale, scale);
if (scale >= 1f)
Destroy(gameObject);
}