- Home /
Unity 2D Topdown Game - Knockback on triggerenter
I am trying to create a basic knockback function, so when the enemy has had a collision, he will be pushed away. As the very simple person I am; I decided to go for a easy-to-understand, lazy route; when OnTriggerEnter2D, transform.translate (Vector.Up * knockBack); But the problem here is that the enemy is going to be continuously knocked upwards regardless of the position that he was being hit from. So since I have 4 different attack animations (attackUp, attackDown, attackLeft ect.), I decided to change the direction of the knockback depending on the animation that is currently being run on the player's animator. Here is the script that the enemy carries:
void OnTriggerEnter2D(Collider2D other) {
if (other.gameObject.tag == "Player") {
Debug.Log ("we found a player");
transform.Translate (Vector2.right * jumpBack);
if (other.GetComponent<Animator>().GetCurrentAnimatorStateInfo (0).IsName ("Player_AttackUp")) {
Debug.Log ("Up");
transform.Translate (Vector2.up * jumpBack);
}
if (other.GetComponent<Animator>().GetCurrentAnimatorStateInfo (0).IsName ("PlayerAttack_Left")) {
print ("left");
transform.Translate (-Vector2.right * jumpBack);
}
if (other.GetComponent<Animator>().GetCurrentAnimatorStateInfo (0).IsName ("PlayerAttack_Right")) {
print ("right");
transform.Translate (Vector2.right * jumpBack);
}
if (other.GetComponent<Animator>().GetCurrentAnimatorStateInfo (0).IsName ("PlayerAttack_Down")) {
print ("down");
transform.Translate (-Vector2.up * jumpBack);
}
It's still wasn't working, the script detects the trigger along with the "player" tag (I tested this using Debug.Log) but nothing is happening with the animations. I've made sure that all the names are corresponding to the right names of the animations in the animator.
The problem lies in my "if" statement.
I'm not 100% sure on the current route I am taking with this to achieve the knockback feature I am aiming for, I am sure that there are probably many other ways to accomplish this task... if you know any of them, please tell me.
Your answer
Follow this Question
Related Questions
Changing how my character looks depending on his current lifes. 2 Answers
How to change animation's speed in C#? 2 Answers
Unity 2d, Need help with Player Sliding when Swiping Down 0 Answers
How can i pay a animation again and agan? 1 Answer
How to play one animation single time and then loop second animation? 0 Answers