0 votes

I have a 3D object (an enemy) and I want to tell if the player is behind or in front of them.
I'm not sure how to do it.

Any help is welcome

I've tried this (eyeRot is the rotation of the enemy)

    if(eyeRot>-1.2 && eyeRot<1.2):
    print("PLAYER INFRONT: " + str(eyeRot) )
    get_node("Sprite3D").show()
else:
    print("BEHIND: " + str(eyeRot) )

But this doesn't work, as it prints positive if the player is in front or behind, and only prints negative if the player is to one of the sides.

What I'm trying to do is a basic cone of sight.

in Engine by (22 points)

1 Answer

–1 vote

If you want to know if the player is in front or behind a node, simply do a dot from the difference of position between the two nodes and the front axis of the object.

For instance, if the front axis of the object is Z, calculate the dot of the player.pos-object.pos on this Z vector. If it's negative, then the player is behind the object. And with that you can even simulate a cone of sight. You simply have to calculate the difference of position and dot it on the X axis of the object. That gives you the 2 sides of a right triangle and therefore the angle on the horizontal plane.

by (698 points)

Thanks,
But, I'm a bit sure how to do this.

I know the dot product

is enemy.gettranslation().dot(player.gettranslation())

but how do I set that to the z axis.

Thanks for the help.

Actually the dot product must be done relatively to the enemy and not to the center of the world.
You can get the absolute z axis from enemy by calling enemy.getglobaltransform().basis[2], which returns you a Vector3 of the Z axis. And only then you can make a zvector.dot(playerrelativeposition), where playerrelativeposition is the player.gettranslation()-enemy.get_translation().
You see, the z vector is used to define the center axis of the sight cone. So any relative vector opposite to this vector would be behind the enemy, and their dot product will always be negative. And they must be relative vectors since a vector always starts from (0,0,0). That's why you must dot the difference of position between the player and the enemy and not dot their actual positions, which are relative to the world (no point to check if the player is behind the world, right?).

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.