Home > Net >  How can I prevent the enemy from following me if we are not in the same tube?
How can I prevent the enemy from following me if we are not in the same tube?

Time:02-02

I am making a game where a mouse is followed by a snake in some tubes. I got down the part where the mouse gets followed, the problem I am having is that sometimes the snake follows the snake even though we are in 2 different tubes, just because I am in front of him from the calculation I am making.

How can I detect if the snake has a wall in front of him, and not the mouse?

This is my code so far:

Vector3 distance = player.position - transform.position;
float dot = Vector3.Dot(distance, transform.forward);
if (dot < 5 && dot > 3)
{
    agent.destination = player.position;
}
else
{
    agent.destination = goals[0].transform.position;
}

CodePudding user response:

Sounds to me like you want the agent to only follow you while it can "see" you

=> You could probably check this via a Physics.LineCast

Returns true if there is any collider intersecting the line between start and end.

Also btw those 3 < dot < 5 sounds quite arbitrary. I would rather normalize the vectors and then Vector3.Dot

For normalized vectors Dot returns 1 if they point in exactly the same direction, -1 if they point in completely opposite directions and 0 if the vectors are perpendicular.

var distance = player.position - transform.position;
var dot = Vector3.Dot(distance.normalized, transform.forward);
// tweak this value according to your needs
if (dot >= 0.5f) // = 45°
{
    <SEE BELOW>
}
else
{
    agent.destination = goals[0].transform.position;
}

or alternatively you could also directly check angles if this reads easier for you

var distance = player.position - transform.position;
var angle = Vector3.Angle(distance, transform.forward);
// tweak this value according to your needs
if (angle <= 45f)
{
    <SEE BELOW>
}
else
{
    agent.destination = goals[0].transform.position;
}

Then replace <SEE BELOW> by e.g.

    // now additionally check if there is a wall in between
    if(Physics.LineCast(transform.position, player.position, WallsLayerMask))
    {
        agent.destination = goals[0].transform.position;
    }
    else
    {
        agent.destination = player.position;
    }
  • Related