- Home /
Enemy following AI doesnt collide.
Hi, Im currently working on a 2d rpg game. I have a enemy script that is following the player with Vector2.MoveTowards. But my problem is that the enemies ignore collsion with objects when the player is behind the object. Is there a way to improve my follow script or can i create my own collision?
follow scipt:`if (Vector2.Distance(transform.position, playerPos.position) < distance){ transform.position = Vector2.MoveTowards(transform.position, playerPos.position, speedEnemy * Time.deltaTime); } else{
if (Vector2.Distance(transform.position, currentPos) <= 0){
}
else{
transform.position = Vector2.MoveTowards(transform.position, currentPos, speedEnemy * Time.deltaTime);
}
}`
I'm not sure what you mean they ignore collisions, are you not using colliders and rigidbodies?
Answer by Tinglee82 · Jun 20, 2021 at 07:08 AM
If you want to move a transform while taking into account scene collisions, you shouldn't set transform.position because that negates all the physics. I assume that you have both Collider and RigidBody components added to your enemy object. You could try using the MovePosition in Rigidbody instead:
public class YourEnemyClass : MonoBehaviour
{
public float speed;
private Rigidbody rb;
public void Start()
{
rb = GetComponent<Rigidbody>();
}
public void Update()
{
if (Vector2.Distance(transform.position, currentPos) <= 0){
}
else{
var _targetPosition = Vector2.MoveTowards(transform.position, currentPos, speedEnemy * Time.deltaTime);
rb.MovePosition(_targetPosition);
}
}
}
You dont know how much this helped me:) Thank you so much!!