Sumtinlazy
Sumtinlazy

Reputation: 347

Using parentheses for Arithmetic inside if Statement Javascript

Im trying to use the distance formula inside of my javascript game, however I am having trouble using parentheses or any equivalent of them inside of an if statement.

Distance formula: distance = sqrt (x1-x2)^2+(y1-y2)^2

if((sqrt(xOne-xTwo)^2+(yOne-yTwo)^2)>32){
  generate();
}

generate(){
  xOne = Math.floor((Math.random()*464)+16); 
  xTwo = Math.floor((Math.random()*464)+16); 
  yOne = Math.floor((Math.random()*464)+16); 
  yTwo = Math.floor((Math.random()*464)+16); 
{

Upvotes: 0

Views: 277

Answers (1)

omarjmh
omarjmh

Reputation: 13896

In your code you should use Math.sqrt and Math.pow:

if (Math.sqrt(Math.pow((xOne - xTwo), 2) + Math.pow((xOne - xTwo), 2)) > 32) {

}

But may I suggest a cleaner approach:

var a = x1 - x2
var b = y1 - y2

var c = Math.sqrt( a*a + b*b );

Upvotes: 1

Related Questions