Running into enemies moves them; how to stop this?
I'm creating a 2D Platformer with enemies. I want to make it so when you run into an enemy they don't move. At the moment, if the player is willing to take collision damage, they can just push enemies out of the way.
The enemies need to be able to move themselves (like pacing) however, so I can't just set it so they can't move at all.
Ideas? I can get more specific and post code if it's helpful as well.
Answer by RobAnthem · Dec 09, 2016 at 10:18 PM
Remove the rigidbody from your enemy. Or make a script that detects the player collision and overrides it.
Would that stop physics from affecting the enemies if I did that? I still want them to hit walls and the player, I just don't want the player to be able to push them. And obviously I still want gravity to affect them.
I'm pretty new, so I don't always understand all the repercussions of everything.
Gravity can be applied without a Rigidbody, and colliders deter$$anonymous$$e collision, essentially unless your Rigidbody physics actually utilize physics and aren't an animation, then it isn't necessary. However, Rigidbodies do provide some nice aspects, and as such I'd still recommend finding a way to use them. $$anonymous$$y best suggestion would be to do this:
void OnCollisionEnter(Collision collision)
{
Collider playerCollider = GetComponent<playerScript>().playerCollider;
if (collision.collider == playerCollider)
{
rigidbody.is$$anonymous$$inematic = true;
rigidbody.velocity = Vector3.zero;
hitByPlayer = true;
}
}
void Update()
{
if (rigidbody.is$$anonymous$$inematic == true)
{
rigidbody.is$$anonymous$$inematic = false;
}
}
Thanks, I'll give that a shot. I ended up turning up the mass on their rigid bodies so they can't be moved, but your way seems more elegant.