- Home /
on mouse over and at a distance
I currently have a script that opens a door when you press the e button but it opens every door on the level and I just wanted to open the one right in front of me. whats the easiest way to do this? should i do it on mouse over or only at a certain distance or a combination or some other method?
heres the script
function Update () { if (Input.GetKeyDown("e")) {
animation.Play("dooropen"); } }
Thanks!
Answer by Flynn · Jan 19, 2011 at 01:36 AM
Unfortunately, for the kind of functionality you want, you need to change how your code works. Your player has to be what opens the door. How can this be done?
First, add the following script to all of your doors.
public function openSaysMe()
{
animation.Play("dooropen");
}
Name that script Door.
Then, in your player-code, do this.
function Update() { if (Input.getKeyDown("e")) { openClosestDoor(); } }
function openClosestDoor() { var doors : Door[] = FindObjectsOfType(Door) as Door[]; var ldst = Mathf.Infinity; var closest = null; for (var i = 0; i < doors.Length; i++) { var dst = Vector3.Distance(transform.position, doors[i].transform.position); if (dst < ldst) { closest = doors[i]; ldst = dst; } } if (closest != null) { closest.openSaysMe(); } }
Note: Code written from memory. May require tweaking.
Points to Flynn for a good example. @The OP: Note however that with this code, if you're standing right in front of a door but looking at another door that's in front of you but a little farther away, the door behind you will open, which may not be the desired behavior (which is one of the reasons I suggested raycasting).
Answer by Jesse Anders · Jan 19, 2011 at 01:36 AM
should i do it on mouse over or only at a certain distance or a combination or some other method?
Yes.
In other words, use whatever method works and gives the desired results. For example, if the door has a collider attached to it, you could use one of the mouse callback functions (as you mentioned), or you could raycast forward from the player position and only open the door during updates when the raycast hits the door in question.