" from this "---".My current code goes like this:
let middleX = (fromX + toX)/2;
let middleY = (fromY + toY)/2;
triangle(middleX,middleY+5,middleX+5,middleY,middleX,middleY-5);
line(fromX , fromY, toX, toY);
As you can anticipate, this doesn't work with rotations.I need help :).Thanks for your attention.
你可以
atan2()
来计算两点之间的旋转。push()
隔离坐标空间(局部旋转而不影响草图的其他部分(如线))。rotate()
弧度:它以弧度为单位取角,这就是 atan2()
返回下面是一个基于你的片段的例子。
let fromX = 200;
let fromY = 200;
let toX = 300;
let toY = 100;
let triangleSize = 5;
function setup() {
createCanvas(400, 400);
}
function draw() {
background(220);
// test: change to position
toX = mouseX;
toY = mouseY;
let middleX = (fromX + toX) / 2;
let middleY = (fromY + toY) / 2;
// calculate the angle between from -> to points
let angle = atan2(toY - fromY, toX - fromX);
// isolate coordinate system (indenting is purely visual, not required)
push();
// move to central position
translate(middleX, middleY);
// rotate from translated position
rotate(angle);
// render triangle
triangle(0, triangleSize, triangleSize, 0, 0, -triangleSize);
pop();
line(fromX, fromY, toX, toY);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/p5.js/1.0.0/p5.min.js"></script>
注 变换的顺序(平移、旋转、缩放)很重要。(例如,如果旋转,那么平移三角形将落在不同的位置)
此外,您还可以在默认情况下将三角形指向右边,这与0弧度的旋转很好地对齐。