- Home /
Detect whether the mouse has moved from left to right?
I'm editing the melee system from UFPS.
As is stands, the system will currently play one of two melee animations- it does this by randomizing the chance that animation 1 or 2 will play.
What I'd like to do is instead tell it to play animation 1 if the mouse cursor is travelling from left to right, and animation 2 if the mouse cursor is travelling up or down.
I'm not so much looking for code (although any suggestions are welcome), more so just some general suggestions as to what people think will be the most efficient way of achieving this?
Any help is much appreciated!
Answer by IgorAherne · Jul 20, 2013 at 04:19 PM
if(Input.GetAxis("Mouse X") == -1){
//play animation for left move
}
if(Input.GetAxis("Mouse X") == 1){
//play animation for right move
}
if(Input.GetAxis("Mouse X")){
//play animation whenever any input from mouse is obtained
}
same for Y
///////////////////////////
//in case u need to define a movement, such as a swing of sword (definite move from left to right in some period of time), try this:
///////////////////////////
var _Swoosh : int;
_Swoosh += Input.GetAxis("Mouse X")*Time.deltaTime*2;
var newTime : boolean = true;
if(newTime){
var currTime = Time.time + 3;
newTime = false;
}
if(currTime < Time.time){
if(_Swoosh > 5 ){
//right swing animation
}
if(_Swoosh < -5){
//left swing animation
}
else{
_Swoosh = 0; //reset back to zero
newTime = true;
}
}
//it's all about the time; right now it should be in seconds, you might want to play around with milliseconds
//Igor Aherne
Only a $$anonymous$$or tweak to the code required to get this working, thanks Igor!
Answer by robertbu · Jul 20, 2013 at 04:03 PM
One way is to use an axis. The default setup of a new project defines two you can use Mouse X, and Mouse Y.
var horz = Input.GetAxis("Mouse X");
var vert = Input.GetAxis("Mouse Y");
Now horz and vert will contain values between -1 and 1. The sign of the value determines which direction the mouse is traveling. You can compare the absolute values of 'horz' and 'vert' to determine whether the movement is predominantly vertical or horizontal (though they both can go to 1/-1 fairly easily).
Another solution is to track the mouse position from the previous frame. If you subtract the previous mouse position from the current mouse position you will get the velocity of the mouse. The sign of the x and y values will be the direction it is traveling. Like the solution above, you can check the absolute value of x against the absolute value of y to see which is the predominant direction.