user3447711
user3447711

Reputation: 1

calculating distance between clicks with hypotenuse

I have some code which calculates the position of an object when clicked and moved, but now I need to find the distance between clicks- for example, how far the object moves the next time I click it. I know it involves calculating the hypotenuse, and I should use use Math.pow() to get squaring use sqrt() to get the hypotenuse, but I can't find a good example of this or get it to work. Thanks for any help, here is the code I am referencing.

$(document).ready(function () {
     var i = true;
     var clickedImage;
     var initialX;
     var initialY;
     $('.square').click(function (e){
         initialX = e.pageX;
         initialY = e.pageY;
         clickedImage = this;
     });
     $(document).on('click', function () {

         $(this)[i ? 'on' : 'off']('mousemove', follow);
         i = !i;
     });

     function follow(e) {
         var xPos = e.pageX;
         var yPos = e.pageY;

         var distanceX = xPos - initialX;
         var distanceY = yPos - initialY;

         $("#squarelocation").html("The square is at: " + xPos + ", " + yPos + "pixels");
         $('#squaredistance').html("Distance from origin: " + distanceX + ", " + distanceY);
         $(clickedImage).offset({
             left: e.pageX,
             top: e.pageY
         });

     }
 });

http://jsfiddle.net/FW9jV/1/

Upvotes: 0

Views: 34

Answers (1)

microtherion
microtherion

Reputation: 4048

No need for pow(). Something like Math.sqrt(distanceX*distanceX+distanceY*distanceY) should do.

Upvotes: 0

Related Questions