How to open a door by the mouse click?
I'd want to create a door which can be opened by pressing the left mouse button but with two other conditions: the player must be close to the door and must be looking at it (by simply pointing the center of the view). I've watched many tutorials and I know that first I must set the pivot of the door, I've already done this but I don't know how to proceed. Could someone help me? Maybe by posting the code that I have to use?
Answer by mj321 · Aug 31, 2016 at 05:33 PM
This is stripped down code from one of my projects. The general idea is to cast a ray from the camera position through the center of the screen into the scene and check which object is hit first. If this object is tagged "Door" and you're close enough, you should open the door.
Untested, but this should get you started.
using UnityEngine;
using System.Collections;
public class OpenDoor : MonoBehaviour
{
public float max_door_distance = 1.0f;
void Update ()
{
if( Input.GetKeyDown(KeyCode.Space) )
{
// your camera must be tagged "MainCamera" in order to use "Camera.main"
Ray ray = Camera.main.ScreenPointToRay( new Vector3(Screen.width/2, Screen.height/2, 0) );
RaycastHit hit;
if( Physics.Raycast(ray, out hit, 10.0f ) )
{
// this assumes a first person perspective (camera position = player position)
// if this is not the case, use player position instead of camera position here
if (hit.collider.tag == "Door" && Vector3.Distance(Camera.main.transform.position, hit.point) < max_door_distance)
{
Debug.Log("open door now");
}
}
}
}
}
Your answer
![](https://koobas.hobune.stream/wayback/20220612091930im_/https://answers.unity.com/themes/thub/images/avi.jpg)