在鼠标拖动上旋转

Rotate on mouseDrag

您好,我想在 mouseDraggedmousePressed 上旋转网格。我的代码正在运行,但是当我停止鼠标按下时,旋转将转到起点而不是重新绘制网格。请指导我完成拖动或鼠标按下到终点后如何重绘网格?

这个问题是因为变量angle声明为本地变量,并且在每一帧中都初始化为0。

将变量声明移至全局范围。例如:

let angle = 0;

function draw() {

    // [...]

    if (mouseIsPressed) {
        angle =  atan2(mouseY - height / 2, mouseX - width / 2);
    }

    // [...]
}

根据评论延期

how can i start dragging again from its end position

使用mouseReleased()事件回调来管理角度。 添加永久角度和当前角度:

let permanent_angle = 0;

function  mouseReleased() {
    let angle =  atan2(mouseY - height / 2, mouseX - width / 2);
    permanent_angle += angle;
}

function draw() {

    // [...]

    let current_angle = 0;
    if (mouseIsPressed) {
        current_angle =  atan2(mouseY - height / 2, mouseX - width / 2);
    }

     translate(width / 2, height / 2);
     rotate(permanent_angle + current_angle);
     translate( -width / 2 + 20, -height / 2 +20 );

     // [...]
}