2D Toolkit Forum
2D Toolkit => Support => Topic started by: k3ch0ng on March 01, 2012, 04:33:02 pm
-
Hi, how would I get the sprite to play a new animation once a trigger event occurs ?
e.g. my character collects stars, i want the stars to sparkle then vanish ( the trigger code is within the charcter )
public void OnTriggerEnter(Collider trigger)
{
switch (trigger.gameObject.name)
{
case "pfWall":
break;
case "pfStar":
trigger.gameObject......
break
}
}
-
You need to get the tk2dAnimatedSprite component.
tk2dAnimatedSprite sprite = trigger.gameObject.GetComponent<tk2dAnimatedSprite>();
sprite.Play(...)
If you need it to sparkle and then vanish, I suggest using a coroutine to play the animation, wait until it finishes, and then disable the gameObject. Something like this...
IEnumerator PlayStarAnimationAndVanish(GameObject target)
{
tk2dAnimatedSprite sprite = target.GetComponent<tk2dAnimatedSprite>();
sprite.Play("animation");
while (sprite.isPlaying())
{
yield return 0;
}
target.active = false;
}
and in your code,
StartCoroutine(PlayStarAnimationAndVanish(trigger.gameObject);
Also don't forget that you probably want to inhibit collisions as soon as the animation has started playing, as it will keep triggering again and again - you can do this by setting the collider to "none" on the frames of animation, or simply coding it in the coroutine above.
Hope that helps,
unikron
-
Thanks that help alot.
To detect if the animation has stopped i just raise another event. Is this a good idea ? Also anyway to get what the animation string is rather than the index ?
tk2dAnimatedSprite animSprite = trigger.GetComponent<tk2dAnimatedSprite>();
animSprite.Play("sparkle");
animSprite.animationCompleteDelegate = SparkleFinish;
private void SparkleFinish(tk2dAnimatedSprite sprite, int n)
{
sprite.renderer.enabled = false;
Destroy(sprite.gameObject);
}
-
Using another event is fine, too.
You can get the animation name by doing
animSprite.CurrentClip.name