Hello Guest

Author Topic: Getting access to the spriteanimation from a trigger event  (Read 9566 times)

k3ch0ng

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 8
    • View Profile
Getting access to the spriteanimation from a trigger event
« 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
      }
   }

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: Getting access to the spriteanimation from a trigger event
« Reply #1 on: March 01, 2012, 06:32:51 pm »
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...

Code: [Select]
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

k3ch0ng

  • 2D Toolkit
  • Newbie
  • *
  • Posts: 8
    • View Profile
Re: Getting access to the spriteanimation from a trigger event
« Reply #2 on: March 01, 2012, 08:07:26 pm »
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);
    }

unikronsoftware

  • Administrator
  • Hero Member
  • *****
  • Posts: 9709
    • View Profile
Re: Getting access to the spriteanimation from a trigger event
« Reply #3 on: March 02, 2012, 02:17:31 pm »
Using another event is fine, too.

You can get the animation name by doing
animSprite.CurrentClip.name