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. – Mangata Mar 08 '23 at 05:59Continuous
collision detection? Also changing the rigidbody to either Dynamic or Kinematic body type makes no difference... – IronWaffleMan Mar 08 '23 at 06:04Vector2.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? – Mangata Mar 08 '23 at 06:29FixedUpdate
, same result. I haven't noticed anything depending on framerates. @Zibelas, I triedMovePosition
like this:rb.MovePosition(Vector2.MoveTowards(transform.position, target.transform.position, step));
but it still went through the walls exactly the same way. – IronWaffleMan Mar 09 '23 at 01:18MovePosition
and settingBody Type
toDynamic
. I had it onKinematic
which was enabling the thing to go through the walls. – IronWaffleMan Mar 09 '23 at 02:36