- Home /
Opening Door With Raycast
Ok so i have a script in which when the player is so far from the door and presses an Interact key the door they are standing front of opens. Every thing i have seems to be working just fine, except the door wont open without the player being right in front of the door, and i don't know what to do. If someone could help me figure this out that this would that would be awesome.
using UnityEngine; using System.Collections;
public class Door : MonoBehaviour {
private float distance;
private GameObject player;
private Ray ray;
void Start () {
player = GameObject.FindGameObjectWithTag ("Player");
}
void Update () {
distance = Vector3.Distance(transform.position, player.transform.position);
ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Input.GetButtonDown("Interact") && distance < 20 && Physics.Raycast(ray, out hit) && hit.collider.gameObject.tag == "Door") {
animation.Play("DoorOpening");
}
}
}
Do you have this script attached to your player GameObject? Also, do you have another script attached to your door GameObject? I am trying to creating this functionality in my project and am having a good deal of trouble. I want to make sure that I have my script placement correct.
Answer by bennett_apps · Sep 15, 2018 at 06:29 PM
A better/simpler way to detect door is to put a big sphere trigger on the door, and put something like this on the player:
void OnTriggerEnter (Collider col) {
if (col.tag == "Door") {
col.GetComponent<Animator>().SetBool("OpenDoor", true);
}
}
Or similar. Does that make sense?
Something like "Interaction $$anonymous$$anager" attached to the same gameobject as player. All interactable objects in scene have trigger colliders of desired form and dimensions, inside interaction manager you check in onTriggerEnter
for a custom "interactable" componnet, door could have some component drived from base interactabe class and implement own custom interaction behaviour. Lastly, you can have unified UI working in tandem with your interaction manager
Answer by karljj1 · Feb 24, 2015 at 10:55 PM
perhaps try a larger value than 20 for your distance check. You can also pass a distance value into your Physics.Raycast instead of performing the check yourself. This is a better solution as your currently checking the distance from the door pivot.
Also make sure nothing is blocking your raycast getting to the door such as another collider.
Your answer
Follow this Question
Related Questions
Raycasting fail 1 Answer
Player have to stop when hit a corner 0 Answers
Mouse Over Wont Work on Bone Animated Meshes. 1 Answer
Animated Object phases through Player 2 Answers
3d animation controller 0 Answers