PDA

View Full Version : Java bezier path


ast3r3x
2009-04-12, 21:32
I'm working on an animation for one of my classes and I'd like to move my objects along a bezier path so it looks better than just a line. However I haven't really found a way to do this without using (and I don't know java super well) java3d stuff.

Even if there is a way though I'm not exactly sure it would even solve my problem. Since I need to move things along the curve/path, I'd need to be able to find points at certain intervals. Sure, the beginning, end, and midpoint would be easy to do. However is there an easier way to find like 11% (random) of the way through the path other than doing midpoints of midpoints and working your way down to whatever interval you want?

I guess my real question other than if someone knows an easy way in java to move an object along an bezier path, is how do you figure out a point 11% (whatever) along a line between two points?

ast3r3x
2009-04-13, 17:07
Ok, so the internet wasn't much help, and I decided just to toughen up and figure it out myself.

So it actually is all pretty much simple trig to figure out how to draw and therefore get points on a bezier curve. Just if anyone ever needs this or could find it useful I'll post the basic code to plot a point along the curve.

All you need to do is pass an array of points (2 or more, yeah yeah I don't check that here) and the distance (distance ∈ [0,1]) and it'll do the rest at plotting the single point along the curve.


protected Point getPointOnBezierCurve( Point[] points, double distance )
{
if( points.length > 2 ) {
Point p;
Point newPoints[] = new Point[points.length-1];
for(int i = 0, j=points.length-1; i<j; i++) {
p = this.getDistancePoint( points[i], points[i+1], distance );
newPoints[i] = p;
}

return this.getPointOnBezierCurve( newPoints, distance );
} else {
return this.getDistancePoint( points[0], points[1], distance );
}
}

protected Point getDistancePoint( Point p1, Point p2, double distance)
{
double slopeRise = (p2.y - p1.y);
double slopeRun = (p2.x - p1.x);
double hypotenuse = Math.sqrt( Math.pow(slopeRise, 2) + Math.pow(slopeRun, 2));

double angle = Math.asin(slopeRise/hypotenuse);

Point point = new Point(
(int) Math.round( p1.x + slopeRun*distance ),
(int) Math.round( p1.y + slopeRise*distance)
);

return point;
}
}