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?
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\$Continuous
collision detection? Also changing the rigidbody to either Dynamic or Kinematic body type makes no difference... \$\endgroup\$Vector2.MoveTowards
executed inUpdate()
instead ofFixedupdate()
? If it does inUpdate()
, 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\$