- Home /
Starting a 2D animation on a trigger
Making a game where you play as a character made of fire. I want to make it so when the player jumps into the torch, the torch lights and the fire animation appears and plays. Here is what I have coded so far, I just can't figure out how to only start playing the animation once torchIsLit = true
public class lightTorch : MonoBehaviour {
private bool torchIsLit = false;
Animator anim;
// Use this for initialization
void Start () {
anim = GetComponent<Animator> ();
}
// Update is called once per frame
void Update () {
if (torchIsLit) {
Debug.Log ("Torch Lit");
}
}
void OnTriggerEnter2D(Collider2D other) {
torchIsLit = true;
}
}
Answer by Hellium · Jul 08, 2015 at 07:16 PM
Why don't you simply play the animation inside the OnTriggerEnter2D ?
Depending on the animator (state machine) you have created, you may want to play the animation using a trigger.
In your animator :
[`<newEmptyState>`] ---→ [`<nameOfYourAnimation>`]
with the transition triggered by a trigger parameter.
Then, you call anim.SetTrigger(<nameOfYourTrigger>);
Alright so I did this, and the trigger is working, setting torchIsLit to true, but the animation is playing and on the screen before I even collide with it. I want the torch to have nothing in it until I run into it and then it lights, making the animation start and now visible. Am I doing something wrong?
public class lightTorch : $$anonymous$$onoBehaviour {
//private bool torchIsLit = false;
Animator anim;
// Use this for initialization
void Start () {
anim = GetComponent<Animator> ();
}
// Update is called once per frame
void Update () {
}
void OnTriggerEnter2D(Collider2D other) {
//torchIsLit = true;
anim.SetTrigger ("torchIsLit");
Debug.Log ("Torch Lit");
}
}
$$anonymous$$ake sure the animation is not the default state of the Animator (in orange).
If so, add an empty state (in the animator window : right click > Empty state) and link the Enter state to the empty state.
In fact, it would be better to do like this :
Sorry for poor quality drawing
Update
I got the animation to appear and start once I collide with it now, but when I do the animation breaks. In the animator the bar repeats over and over without completing the animation so it basically stays on one frame and doesn't animate at all. Why would this happen?
Check the conditions of your transitions :
Idle → Light : Disable exit time, add the trigger parameter
Light → Idle : Enable exit time, no parameter
Thank you! It is working now. Before I had "Any State" -> "Light" ins$$anonymous$$d of "Empty State" -> "Light". Switching it fixed the problem, not exactly sure why, but we are golden now :D
Your answer
Follow this Question
Related Questions
Shooter 2D: Character animation only runs once 1 Answer
Smooth transition of position between animations 0 Answers
On/Off Animator using script 2 Answers
How check if an animation trigger is playing? 1 Answer
AnimationEvent triggers twice 3 Answers