- Home /
How to stop Players pushing Enemies
This ought to be a pretty simple answer.....I hope.
So I have a Player, a wall, and an Enemy in a simple top down map.
I have the enemy Run at the player when within Range - upon OnCollisionEnter2D() I have the enemy stop moving and make an attack; OnCollisionExit2D() resumes the chase.
However, the Player can still push the Enemy - and I can't just turn off movement as I did above because I need the player to run away if they want. Playing with the Rigidbody is also difficult as I need the wall collisions to remain Constant.
My question is: What's the best approach here? Should I be focusing on locking down the enemy movement in it's Update Function? Should I be trying to locate the collision direction and preventing the player moving that way? Is there some way of locking down rigidbody behaviour when colliding with gameobjects of a certain tag?
Any help is greatly appreciated......
Answer by AaronXRDev · Nov 06, 2018 at 04:28 PM
That depends, if you don't mind the player being able to run through the enemy, you could just set the enemies to a different collision layer.
There's a guide for that here: Layer-based collision detection
If you want the enemies to block the player from moving, I would probably set the constraints on the enemy Rigidbody when they are standing in one place. You can do that like this:
public Rigidbody rigidBod;
// Use this for initialization
void Start () {
if (!rigidBod)
{
rigidBod = GetComponent<Rigidbody>();
}
//Make the object lock in place
rigidBod.constraints = RigidbodyConstraints.FreezeAll;
}
// Update is called once per frame
void Update () {
if (Input.GetKeyDown(KeyCode.Space))
{
//Allow the object to respond to physics again
rigidBod.constraints = RigidbodyConstraints.None;
}
}
Definitely the second part - Player and enemy charge each other and when they hit, both stop until the player runs away.
So here I'd be using the Enemy OnCollisionStay2D(collision col) to detect if it is in contact with gameObject.CompareTag("Player") and locking the constraints where true, then lifting the constraints on OnCollisionExit().......That sound right?