我使用 Raphael JS 构建了一个由三个元素组成的简单 2D 汽车.为此,我将 body 作为图像和两个轮胎。我将元素分开是因为我希望轮胎在动画中旋转。
var curCar = raphael.image("car.png", /* x */ 0, /* y */ 0, /* width */ 120, /* height*/ 82)
var tires = raphael.set();
tires.push(
raphael.image("tire.png", 2, 50, 32, 32),
raphael.image("tire.png", 84, 50, 32, 32)
);
如您所见,轮胎位于汽车的“底部”并且已经正确对齐。 现在,curCar 遵循使用 Raphael.animate 的路径,效果很好。对于动画的每次更新,我都会将轮胎平移到 curCar 的位置。它看起来像这样:
function animationUpdate (pos) {
curCar.transform("t" + [pos.x, pos.y] +" r"+ pos.alpha);
tires.transform("t" + [pos.x, pos.y ]);
};
“t”代表平移(x,y),r代表旋转。这些值由 Raphael 自动计算。 当沿着直线路径行驶时,这一切都可行,但一旦 curCar 旋转,轮胎的计算就会失败。
一个例子:
curCar 位于位置 x: 100/y: 200 并旋转了 10°。 轮胎被转换为 x:102/y:150 和 x: 184/y: 250。因此 curCar 旋转了 10°,轮胎错位了。
我的主要问题是:
考虑到旋转,如何计算正确的 X/Y 位置? 必须有一个通用的数学公式来执行此操作。
最佳答案
车轮应该进行 w.r.t. 改造。汽车(车身)的旋转中心。需要注意的是,旋转中心可以在任何地方 w.r.t.车。为了简单起见,以下代码假设旋转中心与汽车中心重合。
最后,如果平移和旋转的执行顺序正确,拉斐尔可以处理数学变换。
var paper = Raphael.paper(0, 0, 500, 400);
// tire width
var tw = 10,
thw = tw * 0.5,
// car width
cw = 100,
chw = cw * 0.5,
// car height
ch = 50,
chh = ch * 0.5,
// x of tire 1 w.r.t. car
t1xc = -chw - thw,
// x of tire 2 w.r.t. car
t2xc = -chw - thw,
// y of tire 1 w.r.t. car
t1yc = -chh - thw,
// y of tire 2 w.r.t. car
t2yc = chh - thw;
var car = paper.rect(20, 20, cw, ch),
// car center
cx = car.attr('x') + chw,
cy = car.attr('y') + chh,
// tire 1
t1 = paper.rect(cx + t1xc, cy + t1yc, tw, tw),
// tire 2
t2 = paper.rect(cx + t2xc, cy + t2yc, tw, tw);
// Translate by 100, 100 and rotate by 30 deg
car.transform("...t100,100r30");
// car center post transformation
cx = car.attr('x') + chw;
cy = car.attr('y') + chh;
// Transform tires, with rotation w.r.t. car center
/* Edited - To add wheel rotation about axle (25 deg) */
t1.transform("...t100,100r30," + [cx, cy] + "r25");
t2.transform("...t100,100r30," + [cx, cy] + "r25");
希望这对您有所帮助。
关于javascript - 根据对象,在平移对象时考虑旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16287736/