Handling Collision with Other Slimes

The Slime changes direction if it encounters a wall, but it would be nice if it reacted to other Slimes as well, don’t you think? There are a couple of ways we could approach this. We could set the Slimes on a layer that has no self-collision, so that they would pass through one another. In our case, however, we’re going to have them change direction instead.

If we just adjust the OnTriggerEnter2D() function’s IF statement to include the “Enemy” tag, there’s no guarantee that both enemies will flip. In fact, there’s a good chance that only one of them will. To prevent this, we’re going to tell both of them to change direction at the same time. Update your EnemySlime script with the code in Listing 9.4.

Listing ...

Get Learning 2D Game Development with Unity®: A Hands-On Guide to Game Creation now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.