使用鼠标旋转矩形

Use mouse to rotate a rectangle

我将矩形指向鼠标。我想要的是:当我抬起鼠标并单击并拖动时,矩形进一步旋转。

或者我可以点击任意角来旋转矩形。就像您用手指和 sheet 纸一样。

let angle = 0;

function setup() {
  createCanvas(400, 400);
}

function draw() {
  background(220);

  push();
  translate(150, 150);
  rotate(angle);

  stroke(0);
  strokeWeight(2);
  rect(-100, -75, 200, 150);

  stroke(255, 0, 0);
  strokeWeight(5);
  line(-100, -75, 100, -75);

  stroke(0, 255, 0);
  point(0, 0);

  pop();
}

function mouseDragged() {
  m_angle = atan2(mouseY - 150, mouseX - 150);
  angle = /* MAGIC FORMULA HERE */ m_angle;
}

https://editor.p5js.org/jwglazebrook/sketches/p2pnhPSZE

The Problem:

您的代码存在问题,您需要存储从初始鼠标点击到新拖动点的偏移量。

The Solution:

要修复抖动行为,我们只需存储之前的鼠标角度和方框角度,并将差异与拖动的鼠标角度进行比较。

The Code:

let angle = 0;

function setup() {
  angleMode(DEGREES);
  createCanvas(400, 400);
}

function draw() {
  background(220);

  push();
  translate(150, 150);
  rotate(angle);

  stroke(0);
  strokeWeight(2);
  rect(-100, -75, 200, 150);

  stroke(255, 0, 0);
  strokeWeight(5);
  line(-100, -75, 100, -75);

  stroke(0, 255, 0);
  point(0, 0);

  pop();
}

let c_angle = 0;
let q_angle = 0;

function mousePressed() {
  c_angle = atan2(mouseY - 150, mouseX - 150); //The initial mouse rotation
  q_angle = angle; //Initial box rotation
}

function mouseDragged() {
  m_angle = atan2(mouseY - 150, mouseX - 150);

  let dangle = m_angle - c_angle; //How much the box needs to be rotated
  if (dangle>=360) dangle-=360; //clamping
  if (dangle<0) dangle+=360; //clamping
  angle =  q_angle + dangle; //Apply the rotation
  if (angle>=360) angle -= 360; //clamping
}