Enemy is moving through walls

I’m not very good with javascript, especially with AI. I have an AI script that makes the enemy follow the player, and when the enemy gets to a certain distance, the level restarts. The script works, except my enemy walks through walls. I’ve added a rigidbody, and it still doesn’t work.

var Player : Transform;
var MoveSpeed = 5;
var MaxDist = 10;
var MidDist = 7.5;
var MinDist = 5;
function Start ()
{
}
function Update ()
{
    transform.LookAt(Player);
   
   
    
     if(Vector3.Distance(transform.position,Player.position) >= MinDist){
    
         transform.position += transform.forward*MoveSpeed*Time.deltaTime;
          
    
  
     
          
          
         if(Vector3.Distance(transform.position,Player.position) <= MinDist)
             {
                Application.LoadLevel(1);

  
   }    
   
   }
  

}

It’s because you’re moving via the Transform, not the Rigidbody.

Yup. Moving the transform just moves the object directly, through anything. Using the rigidbody’s velocity will move it using the physics.

Sorry it took a while for me to reply. Anyways, I’ll try that. Thanks

Now the enemy won’t move at all

var Player : Transform;
var MoveSpeed = 5;
var MaxDist = 10;
var MidDist = 7.5;
var MinDist = 5;
function Start ()
{
}
function Update ()
{
    rigidbody.LookAt(Player);
   
   
    
     if(Vector3.Distance(rigidbody.position,Player.position) >= MinDist){
    
         rigidbody.position += rigidbody.forward*MoveSpeed*Time.deltaTime;
          
    
  
     
          
          
         if(Vector3.Distance(rigidbody.position,Player.position) <= MinDist)
             {
                Application.LoadLevel(1);

  
   }    
   
   }
  

}

I’m only new, but would

rigidbody.AddForce (Vector3.forward * MoveSpeed * Time.deltaTime)

work better for you?

1 Like

Depending on what’s wrong that might make it move, but it’s fundamentally changing the nature of what’s going on. Applying a force is not the same as directly moving something, and that’s not a change I’d make except when (re)considering the design of what I’m doing.

Stick Debug.Log(…) messages in each part of your script so you can see what is and isn’t being called. Print the value of Player and print the calculated distance, and the result of your movement calculation. I can’t tell what’s busted, but one of those values will almost certainly be something you don’t expect, and chasing that rabbit down the hole will reveal the cause of your problem.