Push player in direction based on objects movement

In my game I have monsters that push the player around when they get in range. Pushing the player backwards with a front on attack is easy enough

player.transform.Translate(0,0,-1)

but doesn't work so well when the monsters attack you from behind (you end up getting pushed through the monster, which triggers the push function several times and you could end up anywhere).

Is there a way to detect the direction the monster is moving in and push the player in the same direction? Keeping in mind the push function is based on distance from the player and not a collision.

1 Answer

1

You probably want to push the player in the direction of the vector from the monster's position to the player's position, e.g.:

Vector3 direction = player.transform.position - transform.position;
direction.Normalize();
player.transform.Translate(direction * pushAmount * Time.deltaTime, Space.World);

Normalize! That was the code I was missing. Cheers mate, works a charm.