- Home /
Find mouse Velocity
Hello. So, I've been trying to find the velocity of the mouse pointer in unity. Is there a way to find the position of the mouse pointer for this frame and for the frame before?
Answer by Eno-Khaon · Dec 21, 2020 at 11:05 PM
The simplest approach would be to store the current frame's mouse position just after comparing it to the previous frame's position:
Vector3 lastMousePos;
public Vector3 mouseDelta
{
get
{
return Input.mousePosition - lastMousePos;
}
}
void Start()
{
// Initialize the value to avoid an anomalous first-frame value
lastMousePos = Input.mousePosition;
}
void Update()
{
// Use mouseDelta as needed, then update lastMousePos at
// the end of your Update() loop
lastMousePos = Input.mousePosition;
}
If you want viewport coordinates instead, you can divide the X and Y values by Screen.width and Screen.height respectively.
If you want them relative to your camera's viewable area, you can also factor in Camera.rect values to scale the resulting values further (when an even greater degree of normalization is desired).
Edit: Changed "currentMousePos" to "Input.mousePosition" -- It was technically an artifact of rewriting it halfway through the process
It says "The name 'current$$anonymous$$ousePos' does not exist in the context"
current$$anonymous$$ousePos should be Input.mousePosition. Though this should be quite obvious. He explained the concept in an abstract pseudo code way that would work anywhere when you have access to the current mouse position. You should try to understand the concept and not just copy and paste example code :)
Thank you for letting me know. I am sort of a unity noob, so I don't really know all too much about coding in this
Answer by Bunny83 · Dec 30, 2020 at 12:26 AM
Are you actually interested in the mouse speed or the speed of the mouse pointer. If you want the speed at which the mouse is moved, that's directly returned by Input.GetAxis("Mouse X")
and Input.GetAxis("Mouse Y")
. It tells you how much the mouse has moved since the last frame. Of course if you really are interested in the velocity of the mouse pointer, measured in pixel, you have to use something like what Eno showed in his answer.
Your answer
Follow this Question
Related Questions
Normalized Coordinates are Exponentially inccorect 2 Answers
Having a first person player look at the mouse on the y axis 1 Answer
transform.LookAt gives a twist 2 Answers
Mobile controls, gui mouse problem. 0 Answers
troubles with look at mouse script 2 Answers