Distance to Player

Hi,

we created a multiplayer with Unity networking.
I have implemented a function that checks if the player´s mouse is over a door. A GUI-Text appears if the mouse is over (“Press ‘E’ to open the door”). But how can I check the distance between player and door? I know there are different ways. But my problem is to detect the player that actually is looking at the door. U Know what I mean? I hope so :confused:

So the question is simple I hope:

How can i detect the player that is looking at the door to check the distance between this player and the door.

thanks!
MysteriX

Look up the Ray, Physics.Raycast and Physics.RaycastAll in the Unity3D documentation.

One option: Use InverseTransformPoint to figure out both:

Vector3 doorsLocalPosition = playerTransform.InverseTransformPoint(doorTransform.position);
float angle = Vector3.Angle ( doorsLocalPosition, Vector3.forward );
float distance = doorsLocalPosition.magnitude
if (angle < 45f  distance < 10f ) { }//do stuff

In a game of mine, I have a “LookAtController”, maybe that one can help you. It’s far from perfect, but at the time being it’s doing its purpose.

public class ObjectBeingLookedAt {

	private float lookDistance = 1.75f;
	private float lookRadius   = 0.35f;
	
	public Transform transform;
	
	public ObjectBeingLookedAt ( Camera cam ) {
		Ray          lookingRay  = new Ray (cam.transform.position, cam.transform.forward);
		RaycastHit[] raycastHits = Physics.SphereCastAll( lookingRay, lookRadius, lookDistance );
		Physics.Ray

		if ( raycastHits.Length > 0 ) {
			RaycastHit closestRaycastHit = raycastHits[0];
			
			foreach ( RaycastHit raycastHit in raycastHits ) {
				if ( raycastHit.distance < closestRaycastHit.distance ) {
					closestRaycastHit = raycastHit;
				}
			}
			
			transform = closestRaycastHit.transform;
		}
	}
	
}