How to detect if the player is facing an object?

Hi all.
I’m trying to detect if the player character is facing another object using dot product but I can’t seem to get the correct results. The dot product still returns a negative number when the player faces the object.

I’m using dot product instead of a line trace as I want to be able to set a vision arc.

Can you guys see what I’m doing incorrectly?

DEMO

Try printing the forward vector on tick. I seem to recall it isn’t the same as the actor forward vector?

This just print’s out either 1 or -1 depending on which axis I’m facing.

If the dot product returns the inversed result, why don’t you switch the pins where you plug in your player and actor locations?

Here’s the code we use. Should be straightforward to translate to BP.

Looking at your BP might be that you aren’t normalizing both vecs? Not sure…

bool ABasePlayerController::GetIsActorInFrontOfPlayer(AActor* queryActor)
{
	if (queryActor && GetCurrentCharacter())
	{
		// get normalized player to target vec
		FVector playerToTargetVec = queryActor->GetActorLocation() - GetCurrentCharacter()->GetActorLocation();
		playerToTargetVec.Normalize();

		// get normalized player forward vec
		FVector playerForwardVec = GetCharacter()->GetActorForwardVector();
		playerForwardVec.Normalize();

		// get dot product of player to target vec and player forward vec
		// if dot product > 0 then query target is in front of player
		// using 0.1 because near zero is perpendicular and causes strange  results
		if (FVector::DotProduct(playerToTargetVec, playerForwardVec) > 0.1)
		{
			return true;
		}
		return false;
	}
	return false;
}

This is how I do it:

2 Likes

i just use FindLookAtRotation then break the result, if the ABS of the Z is within your vision arc HalfAngle they’re facing it. you could check Y as well if you care about height

Thanks guys. There’s a few suggestions here. I’ll go give them all a try.

(post deleted by author)

This worked, thank you.

1 Like