Enemy movement towards an instanced target position

Hey, everyone! So what I’m trying to do is have an enemy that randomly moves around, casting rays to search for the target. Upon finding that target, I’d like for the enemy to charge the position at which the ray hit the player–that single point–until it collides with something (at which point a 3-second cooldown is activated). The problem I’m having in my current script is that, if the player moves while the enemy charges, it will follow the player until collision.

Given the nature of the enemy, I would like to use LookAt if possible to have it rotate towards that ray point, but it’s not totally necessary right now. This is what I came up with:

``````if (canSeeTarget()){

this.transform.LookAt(target.transform);
rigidbody.drag = 4;
velocity = base_velocity * 150;

}else{

base_velocity.x = Random.Range(1f, 10f);
base_velocity.y = Random.Range(1f, 10f);
base_velocity.Normalize();

velocity = base_velocity * speed;
}

applyVelocity();
``````

For your information, base_velocity is a protected Vector2, and the canSeeTarget(){ just uses a RayCast function which returns as true if it hits the player.

You need to store the position of the raycast hit and use that instead of target.transform. I assume target is the player.

The easiest way to do these changes is to modify your `canSeeTarget()` to `canSeeTarget(out Vector3 targetLocation)`

Then in the method itself, if it returns true, you’ll save the hit location in `targetLocation`. If it returns false, you can leave it at Vector3.zero.

Your canSeeTarget would be something like:

``````public bool canSeeTarget(out Vector3 targetLocation){
targetLocation = Vector3.zero;
//raycastHit = if raycast hits
targetLocation = hit.position;
return raycastHit
}
``````

You’d use the method as follows:

``````Vector3 targetLocation;
if(canSeeTarget(out targetLocation)){
//targetLocation contains the hit location
}
``````