【发布时间】:2018-04-11 00:12:45
【问题描述】:
我有一个小脚本,其中:
- 身体沿着路径移动。
- 当它到达段的末尾时,它会开始围绕其中心旋转,直到它与下一段的切线对齐。
- 然后它开始沿着下一段移动。
一切正常,但我在旋转方面遇到了一个小问题。身体应旋转以与反射/外角对齐。
正如你在下面的 MCVE 中看到的那样,第二次旋转是顺时针的,而它应该是逆时针的。
相反的情况发生在第 3 段。它逆时针旋转,应该顺时针旋转,因为旋转会跟随外角。
我做错了什么?
paper.setup(document.querySelector('canvas'))
// Path
const path = new paper.Path({
segments: [[-100, 300], [100, 300], [100, 0], [0, 100], [-100, 200], [-200, -50]],
strokeColor: '#E4141B',
strokeWidth: 5,
strokeCap: 'round',
position: paper.view.center
})
path.segments.forEach(segment => {
const text = new paper.PointText({
point: [50, 50],
content: `${parseInt(path.getTangentAt(segment.location).angle)} deg`,
fillColor: 'black',
fontFamily: 'Courier New',
fontWeight: 'bold',
fontSize: 15,
position: segment.point
})
})
// Car
const car = new paper.Path.Rectangle(
new paper.Rectangle(new paper.Point(50, 50), new paper.Point(150, 100))
)
car.fillColor = '#e9e9ff'
car.rotationLabel = new paper.PointText({
point: [50, 50],
content: '0',
fillColor: 'black',
fontFamily: 'Courier New',
fontWeight: 'bold',
fontSize: 10,
position: car.position
})
// Car custom
car.currentRotation = 0
car.rotateAroundCenter = function(rotation) {
rotation = parseInt(rotation)
this.rotate(rotation)
this.currentRotation += rotation
}
car.updateRotationLabel = function() {
this.rotationLabel.position = this.position
this.rotationLabel.content = this.currentRotation
}
car.getCurrentRotation = function() {
return this.currentRotation
}
car.isNotAlignedWith = function(rotation) {
return this.currentRotation !== parseInt(rotation)
}
// Animation-along-a-path
let i = 0
paper.view.onFrame = () => {
car.updateRotationLabel()
const rotation = path.getTangentAt(i).angle
const rotationSign = car.getCurrentRotation() < rotation ? 1 : -1
car.position = path.getPointAt(i)
if (car.isNotAlignedWith(rotation)) {
car.rotateAroundCenter(rotationSign)
} else {
car.position = path.getPointAt(i);
i++
if (i > path.length - 1) {
paper.view.onFrame = () => {}
console.log('done')
}
}
}
canvas {
width: 100%;
height: 100%;
background: #666;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/paper.js/0.11.5/paper-core.min.js"></script>
<canvas></canvas>
FWIW 我已经绘制了路径在旋转时应沿其旋转的外部(反射)角度。
注意:每个段上的黑色角文本是该段的切线。
【问题讨论】:
标签: javascript html5-canvas paperjs