So in my script, I now have working audio and such which was what I was aiming for. NOW I am trying to figure out that when I click the MouseButtonDown on the Door button, it works but can happen from any DISTANCE. I basically want a range of maybe half a meter to be able to open the door.
Opening the door with a button like that of course is really… You know… Unrealistic, haha.
If you can help me, it would be very generous of you… If you can not, thank you for at least looking in to my problem.
My main goal is to further develop this script in to something more powerful with more functionality as well as GUI functions.
A quick hack solution is to put a empty game object with a box collider in front of the button at the distance you want to establish as the maximum distance to hit the button. Any click beyond that distance will hit the box collider and not the button. A bit more elegant solution is to test the distance between the player and the button before allowing the button to be pressed. Say your your player is tagged ‘Player’, you could do this in the top of your OnMouseButtonDwon() callback:
if (Vector3.Distance(GameObject.FindWithTag("Player").transform.position, transform.position) > someValue) {
return;
}
Basically, what you are looking for is a distance from your Avatar/Character’s current position to the clicked Collider. Something similar to;
This is an all purpose version of the script, that you would drop on your avatar…
var playerReach : float = .5;
if ( Input.GetMouseButtonDown(0)){
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay (Input.mousePosition);
if (Physics.Raycast (ray, hit)){
//Ok we hit something, is that thing in range?
//transform should be the avatar's
var dist = Vector3.Distance(hit.collider.transform, transform.position);
//Are we within 1/2 a meter along the z?
if (dist.z <= playerReach){
//Strongly typed interaction
var interactiveObject = hit.collider.gameObeject.GetComponent<InteractiveObject>();
if (interactieObject) {
interactiveObject.Touch(gameObject);
}
//Loosely typed interaction
SendMessage("Touch", gameObject, SendMessageOptions.DontRequireReceiver);
}
}
}
//Script to inherit from and add to any game object
public class InteractiveObject : MonoBehaviour {
//Method to implement the touch behavior
public abstract void Touch(GameObject gameObject);
}
Put this on your door button, this works for a nice one off feature, or if refactored as a Trigger based script.
function OnMouseDown(){
Debug.Log("Mouse is down");
//as @Robertbu pointed out
if (Vector3.Distance(GameObject.FindWithTag("Player").transform.position, transform.position).z > .5 /*worth making a variable*/) {
return;
}
if(!this.isOpen){
doorObj.animation.Play("NewOpen");
this.isOpen = true;
audio.PlayOneShot(openSound);
}else{
doorObj.animation.Play("NewClose");
this.isOpen = false;
if (closeSound)
audio.PlayOneShot(closeSound);
}
}