0
\$\begingroup\$

We're developing a game in Phaser as a university project and have come across an obstacle. We need to detect when the mouse is over a line between two points. There are not a lot of lines, definitely fewer then 500. We were thinking of just checking it with line equations on every update call, but that might slow the game down. We haven't found anything useful on google. Should we just stick with the equations or is there a more elegant way?

Cheers

\$\endgroup\$
1
\$\begingroup\$

You can approach this problem backwards.

  • First, find which lines best "bound" your current mouse position. This would (after the first frame) only check the lines closest to the mouse. This is as simple as walking each line and taking the four (or so) that have the closest distance to the mouse cursor.

  • Second, check only these lines when you perform an update until the mouse breaks one of these boundaries

  • Third, only perform the check if the mouse is moving

While you will still be checking the mouse every update (that it is moving) against every "boundary" line, it will reduce the number of lines you're checking against to about 4.

Note: Without knowing properties of the lines (are they random, are they in a grid pattern, etc) this is as helpful as I can get.


A dirtier option would be to draw your lines with a piece of encoded data, such as a special alpha value that the eye doesn't perceive very well, or a special color. Draw your lines first, then (when you draw your cursor) first check if it would be drawn over a pixel with this encoded value. If it would, then you're hitting a line.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.