Detecting speed of the mouse move.

In my game i want the user give the ability to hit objects with the mousecuror. The strength of the hit should be depening on the speed of the mouse.

So if the user moves the mouse very fast to the object, it should get a bigger force. When the user moves the mouse slowly to the object, the force should also be little.

I know how i can add force to an object but i don’t know how to detect the speed of the mouse

Not sure if this is exactly what you’re looking for, but hopefully it will get you started.

using UnityEngine;

public class MouseSpeed : MonoBehaviour
{
    // store how much the mouse has moved since the last frame
    public Vector3 mouseDelta = Vector3.zero;
    
    private Vector3 lastMousePosition = Vector3.zero;
    
    void Update()
    {
        mouseDelta = Input.mousePosition - lastMousePosition;

        lastMousePosition = Input.mousePosition;
    }
}
2 Likes

There’s a very easy way to get this information:

Input.GetAxis("Mouse X");
Input.GetAxis("Mouse Y");

Give you a value where “mouse delta is multiplied by the axis sensitivity.” Input.GetAxis and Input.GetButton/GetButtonDown/GetButtonUp are the preferred means of getting Input in Unity scripting. If you need to know the name of the button/axis you want to read (or want to define your own), check Edit->Project Settings->Input.

1 Like

Is it measured by pixel resolution to check for drag speed power?

1 Like

I believe it’s in World Coordinates, but you can always convert between World and Screen Coordinates (ie Camera.main.ScreenToWorldPoint and the opposite one, although I primarily use ScreenToWorldPoint: Unity - Scripting API: Camera ).

You would just save the position at when the mouse button was first clicked, and then either use a timer or get the final position when the mouse button is released (probably the former). Then subtract the two (in World coordinates probably- your good old simple XYZ rather than pixels) and you’d get your “drag speed power.”

And just in case I wasn’t clear (and I’m pretty sure I wasn’t), I mentioned using ScreenToWorldPoint() and WorldToScreenPoint() in order to get values in relation to the size of the screen- so that it works across all sizes of screens and screen ratios. There are a few ways to use the two to get what you need, but that’s essentially it.

1 Like

It helped! Thanks for the valuable post!