- Home /
why my 2D Knockback feature only moves enemy in Y direction
i want to knock my enemy away from my players current position when i attack but it doesn't seem to work in the x direction.
public class KnockBack : MonoBehaviour {
public float knockStrength;
public float knockTime;
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Enemy"))
{
Rigidbody2D enemy = other.GetComponent<Rigidbody2D>();
if (enemy != null)
{
enemy.isKinematic = false;
Vector2 difference = enemy.transform.position - transform.position;
difference = difference.normalized * knockStrength;
enemy.velocity = difference;
StartCoroutine(KnockCo(enemy));
}
}
}
private IEnumerator KnockCo(Rigidbody2D enemy) {
if (enemy != null)
{
yield return new WaitForSeconds(knockTime);
enemy.velocity = Vector2.zero;
enemy.isKinematic = true;
}
}
}
Where is the transform origin on each of the objects? If the player object origin is higher or lower than the enemy origin than there will be a notable bump in the y direction. If they are equal on the y, than there shouldn’t be anything happening on the y. If you, for example have the enemy and the player as humans walking into each other and you have the enemy with its origin in the stomach and the player with its origin at the feet, when you calculate the direction from one to another, you will have a diagonal vector returned
Your answer
Follow this Question
Related Questions
Isometric Game with 2D assets? 4 Answers
Get node from position isometric 1 Answer
New sprites in 2D projects only? Cannot add in 3D project 0 Answers
Get position from Isometric TileMap 1 Answer
2D Bring closest spites to front 1 Answer