Previous Topic Tutorial Home Page Next Topic
Travelling Car along the Spline

build a URL to import images
URL imgBase = getImportBase();

Create an image behavior of a car by importing a bitmap.
ImageBvr car1Img = importImage(buildURL(imgBase, "car3.gif"));
Car2 is the mirror image of car1 along Y; use this later to keep the sprite upright.
ImageBvr car2Img = car1Img.transform(scale(1,-1));

Get an image moving back and forth along the spline, the spline is well defined between the third knot from the begining (= 0) and the third knot from the end since it is a cubic.
NumberBvr limitNum = knotsNum[numPts - 1]; third knot from end

Evaluator spans the parameter space of the spline and then returns to the beginning. It then repeats.
NumberBvr evaluatorNum = NumberBvr.newUninitBvr();
evaluatorNum.init(until(mod(localTime, limitNum),
timer(limitNum),
until(sub(limitNum, mod(localTime, limitNum)),
timer(limitNum),
evaluatorNum)));

Construct a point2 behavior that goes back and forth along the spline.
Point2Bvr splPt2 =
bSpline(DEGREE, knotsNum, ptsPt2, null, evaluatorNum);

Speed is the speed of traversal of the spline; it switches among three values upon rightButtonDown.
NumberBvr speedNum = NumberBvr.newUninitBvr();
speedNum.init ( until(toBvr(0.6),
rightButtonDown,
until(toBvr(1.2),
rightButtonDown,
until(toBvr(1.8),
rightButtonDown,
speedNum))));

Construct a new point2 behavior that goes back and forth at the rate of "speed" along the original spline. Integrate the speed and invoke substituteTime. The runOnce construct is necessary so that the integration does not get restarted everytime the rightButtonDown event occurs.
splPt2 = (Point2Bvr)splPt2.substituteTime(integral((NumberBvr)speedNum.runOnce()));

Orient the car based on the spline.

The tangent to the spline is its derivative. Notice that the derivative of a point behavior is a vector behavior.
Vector2Bvr tangentVec2 = derivative(splPt2);
Extract the angle between the tangent and the X axis; it is in [-PI, +PI] range.
NumberBvr angleNum = tangentVec2.getPolarCoordAngle();
The quadrant in which the tangent lies is in [0, 1, -2, -1] CCW
NumberBvr quadrentNum = floor(div(angleNum, toBvr(Math.PI/2)));
carImg is always upright as the traversal of the spline takes place
ImageBvr carImg = (ImageBvr)cond(or(eq(quadrentNum, toBvr(0)),
eq(quadrentNum, toBvr(-1))),
car1Img,
car2Img);

construct a car that travels along the spline always upright
ImageBvr movingCarImg = carImg.transform(compose(translate(sub(splPt2, origin2)),
rotate(angleNum)));

Finally, combine all these parts into the final model.
setImage(overlay(movingCarImg,
overlay(cubicCurveImg,
overlay(ptsImg,
overlay(controlPolyImg, solidColorImage(blue))))));
}

private static int DEGREE = 3;
only cubic pathes are supported
private int _numPolys;
number of polynomials in the spline


© 1998 Microsoft Corporation. All rights reserved. Terms of Use.

Previous Topic Tutorial Home Page Next Topic