- Home /
Click drag change animation speed based on dragging speed
I am just looking for a simple example on how to change the animation speed based on the speed of dragging the mouse in circles or up and down etc. But basically the faster the user drags the mouse in circles the faster the animation plays. Obviously I want it to stop animating when no longer dragging.
If anyone can help I would greatly appreciate it!
Answer by NPnpNPnpNP · Jan 26, 2021 at 10:00 PM
You can calculate the distance traveled by the mouse at each frame.
Vector3 lastMousePosition= Vector3.zero;
void OnMouseDrag()
{
Vector3 delta = currentMousePosition - lastMousePosition;
float distance = delta.magnitude;
lastMousePosition = currentMousePosition;
}
OR If you are using the new input system, you can create an action in your Input Actions :
Set the action type to "Value".
Set the control type to "Vector 3".
And select Mouse > Delta as the path.
OR
If you are using the input manager :
Input.GetAxis("Mouse X");
Input.GetAxis("Mouse Y");
So I took what you presented and added the mouse position. Then I just take the Distance and use the distance part in my script. So that if its over a Certain number etc
(Just repasting your code with the mouse section in it:
Vector3 lastMousePosition = Vector3.zero;
void OnMouseDrag()
{
Vector3 currentMousePosition = Input.mousePosition;
Vector3 delta = currentMousePosition - lastMousePosition;
float distance = delta.magnitude;
lastMousePosition = currentMousePosition;
print("distance " + distance);
}
I will paste how I add the animation component later
Ok so I ended up putting it in the update section. I put a Bool variable in my code to basically turn on/off the drag mouse detection. I put the enable into an if statement for Input.GetMouseButton(0) in the update section as well. I also Divide the output from distance so that the value is something that works in the animator instead of giving me numbers like 64.0 etc I get 0.64 and that works with the animators speed. (Also note you will have to declare anim earlier in your script as the animator. Hope this helps someone looking for this answer too! Thank you again @NPnpNPnpNP
if(mouseDragEnable)
{
anim = MainController.PennyChar.GetComponent<Animator>();
Vector3 currentMousePosition = Input.mousePosition;
Vector3 delta = currentMousePosition - lastMousePosition;
float distance = delta.magnitude;
lastMousePosition = currentMousePosition;
//Divide the distance by 100 because otherwise it will be the wrong value
//AnimationBoost will boost the animation speed base
float x = distance / 100f;
anim.speed = x;
}
Your answer
Follow this Question
Related Questions
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Play animation when mouse drag 1 Answer
Check if an animation has played for a certain amount of time? 0 Answers
How to play animation (C#) 3 Answers