- Home /
How to play animations on entering a trigger and pressing a button? (2D)
Hi guys! So, I'm working on a college assignment, and for it I have to have 10 interactable objects in a scene. What I was wondering is, how would I go about making it so that an animation plays when the player is inside a trigger and pressing a key? I have some code here that returns no errors but doesn't seem to work either:
void Start()
{
boardAnim = GetComponentInChildren<Animator>();
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player" && Input.GetKeyDown("space"))
{
boardAnim.SetTrigger("isOpening");
print("key pressed");
}
}
(Had to cut the boardAnim initialization and a bracket at the end for formatting purposes)
Any help with this would be appreciated! :D
Answer by Vicarian · May 13, 2018 at 04:28 PM
OnTriggerEnter and OnTriggerExit fire on the same frame that the trigger event occurs, however, your input will most generally be processed on the next frame, so things just will never line up. So what you want to do is process the trigger event, set a boolean to true, and in your Update callback process the input if they're standing in the trigger:
bool isInTrigger = false;
void Start()
{
boardAnim = GetComponentInChildren<Animator>();
}
void Update()
{
if (!m_isInTrigger)
return;
if (Input.GetKeyDown("space"))
boardAnim.SetTrigger("isOpening");
}
void OnTriggerEnter2D(Collider2D other)
{
if (other.tag == "Player")
m_isInTrigger = true;
}
void OnTriggerExit2D(Collider2D other)
{
if (other.tag == "Player")
m_isInTrigger = false;
}
This worked perfectly, thanks! I should have thought to use a boolean, tbh, but oh well.
Your answer
Follow this Question
Related Questions
2D Animation does not start 1 Answer
I need help with a Controller on a 2D Game for Android with horizontal movement 1 Answer
How to prevent holding down a key to infinitely loop an action? 1 Answer
GetButton will only play animation when held down 2 Answers
Run Animation/Jump animation/Scripting Movement/Animations 0 Answers