0

I'm trying to create a mouse shaking game in Javascript where you try to move the cursor as fast as you can. Ideally, you get a point for each pixel the cursor moves.

However, my prototype is not working as intended. In the prototype, each time the cursor moves on the button, the points are given. It works just as it should (a point per pixel) when I move the cursor slowly, but things start going wrong when I move my cursor more quickly. For example, the button has a height of 300 pixels. Simply swiping down my cursor vertically on the button should have earned me 300 points, but in reality, i'm only earning 6 or 7 points.

I'm trying to figure out why this is happening. Could it be a hardware issue with monitor refresh rates? If the problem isn't the hardware, how can I modify the code to make the game work as intended?

Source code:

<form name='score'><input name='scorer' type='text' value='0' style='border:none; font-size:22pt; text-align:center;' readonly></form><p>
<p id="scorearea"><button style="font-size:32pt;width:100%;height:300px;" onmousemove=document.score.scorer.value++>Prototype</button></p>

jsFiddle of the prototype: http://jsfiddle.net/MADBt/

Applecot
  • 239
  • 1
  • 2
  • 9

2 Answers2

0

You are counting the number of times onmousemove is being called but not the number of pixels the pointer actually moves. You need to do a little more sophisticated: Save the position in which the pointer is located and then each time onmousemove is called: first, calculate the number of pixels actually moved and second reset the pointer position.

0

You are running up against the browser's limit on the frequency with which it reports the onmousemove event. See this StackOverflow answer for more details.

What you ought to do is store the current mouse position after each move, then in your event handler you can calculate the number of pixels moved each time. In jQuery it would look something like this:

var prevX, prevY, score = 0;
$('button').mousemove(function(e) {
    if (prevX === undefined || prevY === undefined) {
        score += 1;
    } else {
        dx = Math.abs(e.pageX - prevX);
        dy = Math.abs(e.pageY - prevY);
        score += Math.floor(Math.sqrt(dx * dx + dy * dy));
    }
    prevX = e.pageX;
    prevY = e.pageY;
    console.log(score);
    $('input').val(score);
});

Take a look at http://jsfiddle.net/MADBt/1/

Community
  • 1
  • 1
Eric P
  • 4,587
  • 6
  • 24
  • 19