distance between two points in processing app?
I try to get the distance between two points in http://processin开发者_如何学JAVAg.org/ is like java but dont works:
d = sqrt ((x2 - x1)**2 + (y2 - y1)**2);
the distance formula is: http://www.purplemath.com/modules/xyplane/dist07b.gif
Java doesn't have an exponentiation operator. Instead, try Math.pow(x, 2) or x*x.
Processing already comes with a function to calculate the distance between two points in 2d and 3d. Just implement dist()
as mentioned in the reference by handing over your x
and y
parameters of both points:
dist (x1, y1, x2, y2);
You've got a couple of things a bit wrong. It should be:
d = sqrt ((x2 - x1)*(x2 - x1) + (y2 - y1)*(y2 - y1));
other options:
d = dist(x1,y1,x2,y2);
or
d = PVector.dist(new PVector(x1,y1),new PVector(x2,y2));
Imagine you're distance as the hypothenuse of a right angled triangle. One side is defined by the X axis (it's length is x2-x1) and the other by the Y axis (it's length is y2-y1). Since the distance is the hypothenuse, and you know the sides, you simply apply Pythagoras theorem:
BC squared = AB squared + AC squared
BC = square root (AB squared + AC squared)
AC = (x2-x1) = dx
AB = (y2-y1) = dy
or
d = sqrt(dx*dx + dy*dy);
According to http://processing.org/reference/ this should work:
d = sqrt ( pow ( x2 - x1, 2 ) + pow ( y2 - y1, 2 ) );
Although I'm not totally clear if you need this in Processing or in Java.
Just use the built-in Processing classes and methods:
PVector x = new PVector(random(width), random(height));
PVector y = new PVector(random(width), random(height));
System.out.println(getEuclidianDistance(x, y))
Use the build in dist function from processing: http://processing.org/reference/dist_.html.
Btw, this is the way it works internally: http://www.google.com/codesearch#Ej56LtI_pY0/trunk/processing/core/src/processing/core/PApplet.java&q=dist%20package:http://processing%5C.googlecode%5C.com&ct=rc&cd=8&sq=&l=3314
精彩评论