-4

I'm trying to create this mini-game where you fight each other. I used two <img>s as the characters and I got the movement down on both of the <img>s but, I want to make it so when the <img>s are touching you have a option to punch them.

All I'm asking is how to test if they are touching. I'm pretty sure I can handle everything else and if not I can look whatever up. I've tried looking it up hundreds of times, but none of them really talking about <img>s only like divs. If they do talk about <img>s it's very confusing.

David Thomas
  • 249,100
  • 51
  • 377
  • 410
Redezure
  • 1
  • 2

1 Answers1

0

One way to check if two <img> elements are touching or overlapping with each other is to utilize the $.position(), $.height() and $.width() functions to retrieve the top-left position, height and width of each element, respectively.

Using these functions, you can then calculate the four coordinates, top-left, top-right, bottom-left and bottom-right, of your image element. Each coordinate should have an x-coordinate and a y-coordinate. Then you will also have to implement your overlap algorithm to check the image elements' coordinates to see if they are touching or overlapping with each other.

You can take a look at this fiddle.

  • The coordinates function calculates the four coordinates of an element.
  • The incomplete overlap function checks the coordinates of the two element.
  • You can slide the second image horizontally by changing the value of the right css property.

Like I said, the overlap function is incomplete; it only checks if the top x-coordinates of both elements touch/overlaps. (Not gonna do the whole thing for you :-))

There may be other simpler ways to do this, but this works for a game that I built.

ivan.sim
  • 8,972
  • 8
  • 47
  • 63
  • 1
    Note: You can also use [getBoundingClientRect](http://stackoverflow.com/questions/442404/retrieve-the-position-x-y-of-an-html-element) method. – Milan Nov 10 '14 at 00:49