2

I'm new to web development and I'm building a game in which the object is to avoid touching animated circles with the pointer. I set this up with a mouseenter event (full JSFiddle below):

$("#"+circleName).mouseenter(function(){
    $(this).attr("class", "redcircle");
    });

This turns the circles red when the user moves the pointer into them. However, when the mouse is stationary, the circles can pass through it safely. Is there a better way to do this?

By changing the mouseenter event to a hover event, the event is triggered when the animated circle touches the stationary mouse. However, there seems to be a delay. Does anyone know why this might be?

This sounds like it's related to the issue found here, which means that it may have to do with the related browser bug:

getting a mouseenter event from a still mouse entering an animated element

Fiddle: http://jsfiddle.net/nbsteuv/6yok3s56/4/

Community
  • 1
  • 1
nb5t3uv
  • 37
  • 5
  • not sure if there are such events you can just fire from JS. I would suggest keeping track of where the mouse is at and check if it is within the bounds of the circles. – RisingSun Aug 24 '15 at 23:47
  • This could help maybe, since you need position - when there is no event: http://stackoverflow.com/questions/2601097/how-to-get-the-mouse-position-without-events-without-moving-the-mouse... or not, actually... :( – sinisake Aug 24 '15 at 23:50

1 Answers1

2

I would store the last mouse position and then whenever a circle moves, check whether it has intersected the mouse position.

var mouseX, mouseY;

$( "#container-element-id" ).mousemove(function( event ) {
  mouseX = event.pageX;
  mouseY = event.pageY;
});

Define a function to calculate whether a point is in a circle ...

function isPointInCircle(pX, pY, cX, cY)
{
    // Do some math here
}

Then, in your animation code, whenever the circle moves, check if there's an intersection ...

if(isPointInCircle(mouseX, mouseY, circle.left, circle.top))
{
    // color circle red
}
raduation
  • 792
  • 5
  • 11
  • Yes, and then OP will need: http://stackoverflow.com/questions/5419134/how-to-detect-if-two-divs-touch-with-jquery, http://stackoverflow.com/questions/8628368/how-do-i-implement-collision-detection-between-a-set-of-div-elements, http://sourceforge.net/projects/jquerycollision/ – sinisake Aug 25 '15 at 00:35