- Home /
Script not function if mouse is on object
I have modified the mouse orbit script from standard assets to function when the left mouse button is down, but how do I make it function only if the mouse is NOT over a certain object in my scene? Here is the modified code:
var target : Transform;
var distance = 10.0;
var xSpeed = 250.0;
var ySpeed = 120.0;
var yMinLimit = -20;
var yMaxLimit = 80;
private var x = 0.0;
private var y = 0.0;
@script AddComponentMenu("Camera-Control/Mouse Orbit")
function Start () {
var angles = transform.eulerAngles;
x = angles.y;
y = angles.x;
// Make the rigid body not change rotation
if (rigidbody)
rigidbody.freezeRotation = true;
}
function LateUpdate () {
if(Input.GetKey(KeyCode.Mouse0)){
if (target) {
x += Input.GetAxis("Mouse X") * xSpeed * 0.02;
y -= Input.GetAxis("Mouse Y") * ySpeed * 0.02;
y = ClampAngle(y, yMinLimit, yMaxLimit);
var rotation = Quaternion.Euler(y, x, 0);
var position = rotation * Vector3(0.0, 0.0, -distance) + target.position;
transform.rotation = rotation;
transform.position = position;
}
}
}
static function ClampAngle (angle : float, min : float, max : float) {
if (angle < -360)
angle += 360;
if (angle > 360)
angle -= 360;
return Mathf.Clamp (angle, min, max);
}
Just FYI: your script is UnityScript/Javascript but you've tagged the question with C#.
Answer by Huacanacha · Nov 22, 2013 at 08:53 PM
OnMouseEnter and OnMouseExit will tell you when the cursor is in front of an object with a collider (provided it doesn't belong to the Ignore Raycast layer. Use these functions to set a flag and only perform your updates when the flag says so:
var isMouseOver : boolean = false;
function Start() {
isMouseOver = false;
}
function OnMouseEnter() {
isMouseOver = true;
}
function OnMouseExit(0 {
isMouseOver = false;
}
function LateUpdate () {
if(isMouseOver && Input.GetKey(KeyCode.Mouse0)){
// ... etc
Note that I don't use UnityScript myself so the syntax might not be 100% correct. I also don't know if there are any cases where the OnMouseEnter/Exit callbacks aren't sent, which would break the toggling of the flag.
Your answer
Follow this Question
Related Questions
Rotating camera around object up/down problem 0 Answers
OnMouseDown on what? Camera Movement Help. 1 Answer
Modified mouse orbit interfering with camera rotation 1 Answer
Calling Functions from another Script 3 Answers
rotate Y axis to face mouse 1 Answer