What I’m trying to do is have a lever which the player can click on to trigger and animation. The problem is, I can’t just do “Input.GetMouseButtonDown” because I need it to happen only when the mouse is over the lever. I am really new to scripting, so examples would be great.
P.S.
I’d also like it if it could only be clicked on from a certain distance, so that the player can’t trigger it from all the way across the map. That’s getting more complex though, so I’m not going to worry about that now, I just want to get the basic function before moving on.
You should use Camera.ScreenPointToRay for that. It creates a ray from the camera towards the position of the mouse.
You can use this ray as a parameter for the Physics.RaycastAll function. This function accepts a distance parameter too. Go to the link, copy the code and use “if(hit.collider.tag == “tag of lever”)” to see if you are looking at the lever. If you are, then you can start the animation.
Thanks, I’m working on getting that into a working script…Would it work to set a GUI texture as the cursor (I’d like the cursor to remain in the center of the screen) and then set the “var ray = camera.ScreenPointToRay (Vector3(X,Y,0));” to the position of the “cursor”?
Also
Since I’m new to scripting, where in the script would I put the “if(hit.collider.tag == “tag of lever”)” bit?
This is a stripped out version of what I ended up using in my project. I’m really new to this and went though the same thing about a month ago. I’m not saying this is the right or even a good way to do this, but it works for me. OnMouseOver is basically a simplified way to doing a raycast, less to type out, but it comes with its own limitations.
function OnMouseOver () {
if ( Input.GetButton("Fire1") ) {
DistanceCheck();
}
}
function DistanceCheck(){
var clickDistance = Vector3.Distance(transform.position, playerPosition.transform.position);
if (clickDistance <= clickDistanceReq){
KeypadStart();
}
}
This code would be placed in a script that’s attached to the lever in your level. In my case, I’m using a keypad, instead. The first function waits to see if the mouse cursor(which is locked to the center of the screen using Screen.lockCursor = true) is over the object. If the user clicks the first mouse button while over the object, it calls another function to check if they’re within a reasonable distance. Earlier in the script, I defined “clickDistanceReq” to a good value. I use Vector3.Distance to see how far the player is from the keypad and compare it to my limit before. If it’s equal or less than the limit, it calls another function to bring up a GUI. In your case, you’d use it to call a function that would open a door or lower a bridge or something like that instead.