- Home /
Right click drag and drop script
Hi guys,
Been working on this one most of the day. It seems relatively simple but it's been giving me a real headache.
Picking up and dropping objects is pretty easy, just use the OnMouseDown + OnMouseDrag. My problem occurs because I want to use the right mouse button, and Unity only has these special functions for the left button.
Here's the code I've got so far. It works, except to pick up the object you need to right-click on it, then left-click and drag to execute the OnMouseDrag function.
var screenSpace; var offset;
function Update() { if(Input.GetMouseButton(1)) { gameObject.GetComponent(Rigidbody).freezeRotation = true; screenSpace = Camera.main.WorldToScreenPoint(transform.position); offset = transform.position - Camera.main.ScreenToWorldPoint(Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z)); } else { gameObject.GetComponent(Rigidbody).freezeRotation = false; } }
function OnMouseDrag() { //if(Input.GetMouseButton(1)) { var curScreenSpace = Vector3(Input.mousePosition.x, Input.mousePosition.y, screenSpace.z); var curPosition = Camera.main.ScreenToWorldPoint(curScreenSpace) + offset; transform.position = curPosition; //} }
How exactly would I go about replacing the OnMouseDrag to that it can be executed with the right mouse button only?
What's stopping you from putting both parts of the script under update()?
Answer by sovalopivia · Jul 27, 2010 at 01:47 PM
You could look into using Event.MouseDrag()
I don't believe that restricts which button is required to be pressed, just a button and mouse movement. However I'm not familiar with it's implementation.
http://unity3d.com/support/documentation/ScriptReference/EventType.MouseDrag.html
Or you could declare a variable for the Script like 'selected' or something and set it to true in the OnMouseOver()
function, like so.
function OnMouseOver(){
if(Input.GetMouseButtonDown(1)) {
selected = true;
}
}
Then within Update() you need to do two things, first check if the right button is still pressed, and second relocate the GameObject to your mouse position. You could set your variable back to false like this.
function Update() { if (Input.GetMouseButtonUp(1)) { selected = false; }
if(selected) {
DoYourStuff();
}
}
Your answer
Follow this Question
Related Questions
how to detect horizantal and vertical drag on screen by mouse.? 1 Answer
Help In Making a SphereCast for 3D Tire! Working RayCast Script included! 0 Answers
Mouse drag horizontally and vertically is not working..? 0 Answers
Trying to trigger multiple objects by holding down the mouse with OnMouseDown 1 Answer
Translate object on y axis 0 Answers