How could I detect if mouse cursor is being "shaken"?

Started by Héctor Bometón, Mon 20/07/2020 19:06:14

Previous topic - Next topic

Héctor Bometón


By "shaking" I mean any repetitive back and forth movement (up-down, left-right ...).

For example, when the player has a "cocktail shaker" as active inventory, I want a sound (or an event) to be triggered when you "shake it" more than a couple of times.

Sorry for posting twice the same day! I don't mean to abuse your generostiy!

Snarky

What we're interested in here is the acceleration of the mouse cursor: that is, how its movement changes. In mathematical terms, this is the second derivative of its position over time.

In other words, we do it in two steps: first we calculate the current motion of the cursor by comparing the (x,y) position between loops. (Meaning, we subtract the mouse x-coordinate of the last frame from the x-coordinate of the current frame, and the same for the y-coordinate.) This gives us a motion (first derivative) vector, e.g. dx_1=12, dy_1=-8 , which means that the mouse moved 12 pixels to the right and 8 pixels up in the last game loop.

Then we do the same thing in the next loop, giving us a new motion vector, let's say dx_2=3, dy_2=4 (meaning that now it moved 3 pixels right and 4 pixels down).

And now to work out the acceleration we take this motion vector and subtract the old motion vector (which gives us the second derivative): ddx_2=3-12=-9, ddy_2=4-(-8)=12.

Now we have to decide whether this acceleration is a "jerk" of the cursor. Depending on exactly how we want it to be detected we can do this in a few different ways, but the simplest is to simply set a threshold and say that if magnitude of the vector is greater than some value, we count it. The magnitude is sqrt(ddx*ddx + ddy*ddy).

All right, but you were talking about repetitive shaking, so: multiple jerks in sequence. We can think of this as a kind of "double-clicking": when we detect a jerk, we set a timer, and then if there's another jerk before the timer times out, that means we're shaking, and continue shaking until the timer runs out (resetting it each time we detect another jerk).

If you need to be able to tell what direction it's shaking, or that it only counts if the shaking is regular (steady rhythm or steady direction) we need to be a bit more clever, but this is the basic idea.

Héctor Bometón



Thank you! I understand the theory completely. I'm not so talented when it comes to code, but I'll try!

milkanannan

Hi Hector,

Check out a game called 'Crave'. Ego can activate x-ray vision by shaking the cursor back and forth. Maybe the developer could help you out with what you need.
Here it is: https://www.adventuregamestudio.co.uk/site/games/game/624/

SMF spam blocked by CleanTalk