- Home /
The question is answered, right answer was accepted
How to get the mouse direction while left click is pressed?
Hi again guys.
I've stumbled a bit in the code and I've had over 8 hours of trying to get this today but I couldn't get to the end of it. I've searched all over and found similar questions but none offered me a good response honestly.
I want to click on an object and while holding the click to know if my mouse is moving up, down, left or right so that afterwards I could perform actions based on these 4 directions.
I've tried to debug it like this, but it doesn't quite get me there. Any help would be greatly appreciated (even a link towards a question that has been answered if this is a dupe):
function Update()
{
if(Input.GetMouseButtonDown(0))
{
OnMouseDrag();
}
}
function OnMouseDrag(){
if(Input.GetAxis("Mouse X") > 0)
{
Debug.Log("X e mai mare ca 0");
}
if(Input.GetAxis("Mouse X") < 0)
{
Debug.Log("X mai mic ca 0");
}
if(Input.GetAxis("Mouse Y") > 0)
{
Debug.Log("y mare ca 0");
}
if(Input.GetAxis("Mouse Y") < 0)
{
Debug.Log("y mic ca 0");
}
}
Answer by robertbu · May 08, 2013 at 12:39 AM
Here is one solution using Vector3.Dot(). There are efficiency improvements that can be made:
#pragma strict
private var v3Pos : Vector3;
private var threshold = 9;
function OnMouseDown() {
v3Pos = Input.mousePosition;
}
function OnMouseDrag() {
var v3 = Input.mousePosition - v3Pos;
v3.Normalize();
var f = Vector3.Dot(v3, Vector3.up);
if (Vector3.Distance(v3Pos, Input.mousePosition) < threshold) {
Debug.Log("No movement");
return;
}
if (f >= 0.5) {
Debug.Log("Up");
}
else if (f <= -0.5) {
Debug.Log("Down");
}
else {
f = Vector3.Dot(v3, Vector3.right);
if (f >= 0.5) {
Debug.Log("Right");
}
else {
Debug.Log("Left");
}
}
v3Pos = Input.mousePosition;
}
Thanks, that's useful but not quite what I need here. I only want it to get my direction based on my first click location. Therefore, when I move the mouse upwards from the initial position do something, when i move the mouse left from the initial position do something else and so on.
If you take out line 34, this will report the relative position based on the current mouse position and the starting position. But that does not sound like what you want. You are going to have to be a lot more explicit. So if I move up three units and right two units, what should be reported? And if I then move back left one unit (I'm still right of the starting position) what should be reported? And do you need this reporting during the entire drag, or only during an On$$anonymous$$ouseUp().
Yes! Thank you, that was exactly what I needed! This works for my specific problem without line 34! $$anonymous$$arking as correct! Thank you for the help!