Keep a separate gamestate object which contains x/y positions of all objects. Each time you draw on the canvas you use these coordinates. You might already be doing this. So lets say enemy.x
and enemy.y
are currently available within scope.
The next thing to do is getting the cursors's x/y position. You can get this by checking the MouseEvent
instance provided by the mousedown
callback.
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent
The MouseEvent
instance contains the clientX
and clientY
properties. These will reflect the coordinates of te cursor based on the client area, not the canvas, so we need to convert this first. Please see this answer:
How do I get the coordinates of a mouse click on a canvas element?
Once you actually got the coordinates. You need to check whether the mouse x/y coordinate is within a certain boundary around the enemy coordinate. This is because modern screens have high resolutions, and most likely no person is precise enough to click that correct 1 pixel area on the screen.
The boundary which is acceptable as valid input is called a "bounding box" and is typically a square or a rectangle the size of the image used to represent the enemy. If the enemy is a 50x50 px image placed on the center of it's x/y coordinate. the bounding box will start at x - 25px, y - 25px and will stretch to x + 25px, y + 25px.
You need to take the bounding box into account and validate whether the user clicked within that region. This will probably look somewhat like.
if(mouse.x >= enemy.x - 25 && mouse.x <= enemy.x + 25 && mouse.y >= enemy.y - 25 && mouse.y <= enemy.y + 25
)`
(from the top of my head).
If the calculated mouse position on click matches that condition can consider that a hit.