Finding the distance between 2 points JavaScript.

Using a constructor point, x and y to find the distance between 2 points, usefull for game programming.


function Point(x, y) {
this.x = x;
this.y = y;
}

function distance(p, q) {
var dx = p.x - q.x;
var dy = p.y - q.y;

return Math.sqrt(dx * dx + dy * dy);
}

var p = new Point(100, 150);
var q = new Point(150, 100);

var dist = distance(p, q);

console.log(dist);

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s