- Home /
C# Track Mouse Cursor Movement Speed
I'm trying to track how fast my mouse cursor is moving. I tried mouseCursorSpeed = Input.GetAxis("Mouse X"); but the values I'm getting are very low despite the fact that I'm moving my mouse really fast. Am I tracking the right value?
public float mouseCursorSpeed;
Void Update(){
mouseCursorSpeed = Input.GetAxis("Mouse X");
}
Answer by Pangamini · Aug 18, 2014 at 08:32 AM
Just comparing mouse position to the last know position isn't enough.
I suggest you create a "physical mouse pointer", an object (not necessarily a gameObject, can be regular class or just 2 vectors) that will try and follow mouse pointer using velocity instead of translation (that is, its position is only changed by velocity*deltaTime and you only change velocity). I think the easiest way for it would be to use Vector3.SmoothDamp (Vector2.SmoothDamp method doesn't exist). You simply use the existing mouse pointer position as target and store the physical mouse position and velocity in other variables. Depending on the other args you pass into SmoothDamp (especially the SmoothTime, i'd leave MaxSpeed at infinity) you will get either smooth or more accurate but perhaps shaky result.
m_physMousePos = SmoothDamp(m_physMousePos, Input.mousePosition, m_physMouseVelocity, 0.3, Mathf.Infinity, deltaTime)
Also, to get a scalar (as you said, no negative values) just calculate the magnitude of the m_phys$$anonymous$$ouseVelocity
Answer by IgnoranceIsBliss · Aug 18, 2014 at 12:38 AM
If your game is running really fast (the FPS is high), you'll be getting a LOT of low values.
Remember that if you want a real 'speed', you'll need to relate the figure to actual time. So for example...
mouseCursorSpeed = Input.GetAxis("Mouse X") / Time.deltaTime;
...will get you a very rough estimate of mouse speed in units-per-second.
In reality, you might want to average the figure out over several frames, since sometimes frame rates can be a little erratic.
Time.deltaTime is the total amount of time (in seconds) elapsed since the last frame. When doing animations, calculating speeds or doing some rough physics, it's invaluable.
I'm getting a lot of negative values as well as positive due to Input.GetAxis("$$anonymous$$ouse X")being where ever the mouse is. I want to make it so I only get positive values to make mouseCursorSpeed function like speed.
Thanks a lot. Your answer really helped me :) I had mouse movement speed issue when I used "Fastest" setting in my build (lower timeDelta slows down the mouse).
Your answer
Follow this Question
Related Questions
C# moveOnMouseClick Rotation 2 Answers
C# Gameobject Rigidbody Mouse Collision 1 Answer
Left Click Script Problems 1 Answer
error CS8025: Parsing error 1 Answer
Get GameObject That Was Last Clicked? 2 Answers