I have an enemy object, and it needs to move around an arena. I also have four Wall gameObjects surrounding this arena, and both the enemy and walls have colliders (not set to isTrigger). This is how I currently move the enemy (this is called in the Update loop):

    float step = moveSpeed * Time.deltaTime;
    transform.position = Vector2.MoveTowards(transform.position, target.transform.position, step);

Works great, except for when it chases a target outside of the arena entirely, ignoring the walls. I'm guessing it's because I'm explicitly setting the position? Is there another way to move it that will obey the colliders?

  • \$\begingroup\$ No, technically speaking, even with setting velocity, adding forces, etc., it still has a chance to break out of the collider, because the physics simulation is discrete. If the movement speed is slow, you can consider setting the speed, but if the speed is fast, you may need to consider CCD. \$\endgroup\$
    – Mangata
    Mar 8 at 5:59
  • \$\begingroup\$ But I've set the enemy's rigidbody2d to have Continuous collision detection? Also changing the rigidbody to either Dynamic or Kinematic body type makes no difference... \$\endgroup\$ Mar 8 at 6:04
  • \$\begingroup\$ Please set the position of the enemy so that the collider of the enemy and the wall overlaps, click to run the game, will the wall push the enemy away? Maybe it's not the movement that's causing the problem, more details and test cases are needed. : ) In other words, does penetration only occur when moving at high speeds or also at very slow speeds? \$\endgroup\$
    – Mangata
    Mar 8 at 6:08
  • \$\begingroup\$ When I start the enemy in the wall it does pop out, yes. The speed is relatively slow; definitely spends more than 1 frame in the wall and yet isn't stopped by the wall at all. \$\endgroup\$ Mar 8 at 6:18
  • \$\begingroup\$ Is Vector2.MoveTowards executed in Update() instead of Fixedupdate()? If it does in Update(), the position setting may be done multiple times between physics simulations, which also causes penetration. It depends on the frame rate. Have you observed that penetration happens more easily at higher render framerates? \$\endgroup\$
    – Mangata
    Mar 8 at 6:29


Browse other questions tagged .