使用鼠标旋转矩形

问题描述 投票:2回答:1

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

或者我可以单击任意角以旋转矩形。就像用手指和一张纸一样。

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

javascript rotation processing angle
1个回答
1
投票

问题:

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

解决方案:

[为了解决抖动现象,我们只需要存储以前的鼠标角度和盒子角度,并将差异与拖动的鼠标角度进行比较即可。

代码:

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
}
© www.soinside.com 2019 - 2024. All rights reserved.