首页 > 解决方案 > PaperJS - 如何沿路径移动并沿路径旋转

问题描述

此处显示的示例显示了如何在 Paperjs 中沿路径移动对象,但如何沿路径正确旋转它们?

在上面链接中显示的示例中,人们建议使用圆圈作为示例。但是一旦更改为矩形new Path.Rectangle(new Point(20,20), new Size(20,20));,您可以看到它沿路径移动,但实际上并未沿路径方向旋转。

如何计算旋转并将其设置为我的对象?

标签: javascriptmathpaperjs

解决方案


为了计算旋转,您需要知道矩形位置处路径的切向量。
这可以使用path.getTangentAt(offset)方法检索。
然后,为项目的旋转设置动画的一种简单方法是在每个帧上设置属性并item.applyMatrix对其false进行动画处理。item.rotation

这是演示解决方案的草图。

// Create the rectangle to animate along the path.
// Note that matrix is not applied, this will allow us to easily animate its
// rotation.
var rectangle = new Path.Rectangle({
    point: view.center,
    size: new Size(100, 200),
    strokeColor: 'orange',
    applyMatrix: false
});

// Create the path along which the rectangle will be animated.
var path = new Path.Circle({
    center: view.center,
    radius: 250,
    strokeColor: 'blue'
});

// On each frame...
function onFrame(event) {
    // ...calculate the time of the animation between 0 and 1... 
    var slowness = 400;
    var time = event.count % slowness / slowness;
    // ...and move the rectangle.
    updateRectangle(time);
}

function updateRectangle(time) {
    // Calculate the offset relatively to the path length.
    var offset = time * path.length;
    // Get point to position the rectangle.
    var point = path.getPointAt(offset);
    // Get tangent vector at this point.
    var tangent = path.getTangentAt(offset);
    // Move rectangle.
    rectangle.position = point;
    // Rotate rectangle.
    rectangle.rotation = tangent.angle;
}

推荐阅读