Without getting too complex, you don't actually check to see if a sprite you drew on the screen hit another sprite you drew on the screen. What you're actually checking is, "If I make a box around the spot where I drew this sprite, and I make another box around the spot where I drew this other sprite, would those two boxes overlap?"
And to answer that question, you need to know information about both boxes. Specifically, you need to know where the opposite corners of those boxes would be. (Usually you use the top-left and bottom right.) Knowing where those corners are, there's some math you can do with those numbers to see if those boxes overlap.
You can also use the x/y coordinates of one corner of the box (usually the top-left) and the width/height of the box. (Because you can just add the width to the x coordinate and the height to the y coordinate to get the new x/y of the opposite corner.)
Usually when you draw a sprite, you know the x/y of where you're drawing the sprite, and you know how wide/tall it is (usually 8x8). Using that info, you can check for overlap.
Here's a visualization I made that shows how the overlap-checking works. It might not be super clear, but hopefully it helps. You can move the boxes in the visualization around with up/down/left/right and E/D/S/F, and pressing X will show the box boundaries.
(I'm sure you'll get some other helpful answers in this thread as well.)
Hopefully the first half of this video helps make it more visually clear:
Basically, if you do that kind of overlap-checking, then you can do something if it does find an overlap. Like this:
function overlap(box1,box1) --do a bunch of math stuff and give back --a true/false whether the two boxes overlap end function _update() if overlap(player,enemy) then --do something here if these two --things overlap. Make a sound? --Subtract a number from the player's --health? Print, "You got hit!" --Whatever you want. end end
If it's the classic 8x8 sprites you want, @FloatyBoi, to check a collision on you can use this:
function collide(x1,y1,x2,y2) if (abs(x1-x2)<8 and abs(y1-y2)<8) return true end
Or change the 8 to a smaller number so near misses are not counted.
Here is a sample. Use the arrow keys to navigate and the 🅾️ key to swap between which target to control, the player or the enemy. Click on
Code▽ below to see source-code.
Hey! I see you want to make the blue one disappear from the screen when colliding, so here's an update on @dw817's cart to make it do just that.
This one simply hides the player and disables collision and movement. Deleting the player is more complicated, but if you would like something like that I can try my best.
[Please log in to post a comment]