2

i'm making a game in jquery/javascript. And the game is to hit one moving object by using your mouse to click on the screen. I have problem with the detection bit. Is there a jQuery/javascript function that can mesure the distance between the center of the two objects at all time? Becasue then i can easily make a control check the distance of the two centers. and se if the collide. They are both two circles.

<div id="box">
        <div id="prepend">
            <div id="hero"></div>
        </div>

        <div id="enemy"></div>
</div>

Where "box" is the area where the game takes place, "hero" the bullet that you are going to hit the "enemy".

OpherV
  • 6,787
  • 6
  • 36
  • 55
Tonton
  • 63
  • 1
  • 7

3 Answers3

5

To get the distance use the formula enter image description here

function getDistance(obj1,obj2){
    Obj1Center=[obj1.offset().left+obj1.width()/2,obj1.offset().top+obj1.height()/2];
    Obj2Center=[obj2.offset().left+obj2.width()/2,obj2.offset().top+obj2.height()/2];

    var distance=Math.sqrt( Math.pow( Obj2Center[0]-Obj1Center[0], 2)  + Math.pow( Obj2Center[1]-Obj1Center[1], 2) )

    return distance;
}

Call using

getDistance($("#obj1"),$("#obj2"));

To check for collision:

function hasCollision(obj1,obj2){    
    return getDistance(obj1,obj2)<obj1.width()/2+obj2.width()/2;
}

Here's a jsfiddle example demonstrating both

OpherV
  • 6,787
  • 6
  • 36
  • 55
0

You can use the following:

var $this = $(this);
var offset = $this.offset();
var width = $this.width();
var height = $this.height();

var centerX = offset.left + width / 2;
var centerY = offset.top + height / 2;

Do this for both and then calculate the difference between those values.

James
  • 2,013
  • 3
  • 18
  • 31
0

There isn't one, but its pretty simple actually:

  1. Get the absolute coords of the current item as well as width and height
  2. Calculate center point (x + width/2, y + height/2)
  3. Do that for both circles
  4. use trigonometric functions to calculate distance between those two points: difference of x in square plus difference of y in square, take the square root of that = distance
  5. if the distance minus the radius of both circles is greater than 0, no collision. If 0: they touch, if smaller than 0, they collided.
Zim84
  • 3,404
  • 2
  • 35
  • 40