How to make the enemy stops according the player position

I’m trying to make the enemy stop his movement case the player stay on same position for a few time, but I dont know where is the error in this code. I know its a very noob question, but i’m noob.

In the class I have the following variables:

public float thinkTime = 0.25f;
private float timeLastTought = 0.0f;
private Vector3 _moveDirection;
private Vector3 _lastTargetPos;
public float speed = 6.0f;

and in update method I have this code:

//wait a little time to simulate thinking time
if(Time.time - timeLastTought > thinkTime) {
	
	//if the player moves left or right, follow him	
	if(target.position.x >= transform.position.x) {		
		_moveDirection = Vector3.right;
	} else if (target.position.x < transform.position.x) {
		_moveDirection = Vector3.left;
	}

	//if the player didn't move or moved a little
	if(	(
			(
			target.position.x <= (_lastTargetPos.x + (_lastTargetPos.x * 0.05f)) &&
			target.position.x >= (_lastTargetPos.x - (_lastTargetPos.x * 0.05f))
			) 
			&&
			(
			target.position.y <= (_lastTargetPos.y + (_lastTargetPos.y * 0.05f)) &&
			target.position.y >= (_lastTargetPos.y - (_lastTargetPos.y * 0.05f))
			)
		)
	   )
	{
		//negate movement to stop
		_moveDirection = -_moveDirection;
		Shoot();
	}
	timeLastTought = Time.time;
	_lastTargetPos = target.position;
}

1 Answer

1

We don’t see how you use _moveDirection, so it is hard to be sure how to fix your code. But I believe that line 26 should be:

_moveDirection = Vector3.zero;

Your logic is a bit convoluted. I think you want something like:

if (Vector3.Distance(target.position, _lastTargetPos) > 0.05f) {
    if(target.position.x >= transform.position.x) {       
       _moveDirection = Vector3.right;
    } 
    else {
       _moveDirection = Vector3.left;
    }
}  
else {
    _moveDirection = Vector3.zero;
    Shoot();
}

It works. Thank you very much!! =D

–