使旋转物体可拖动

时间:2014-12-09 16:04:24

标签: javascript processing

我是Processing的新手,我试图操纵我的矩形对象,以便当光标悬停在其位置上时,用户可以拖动鼠标旋转它。但是,我在定位一个边界框时遇到了问题,这个边界框既包围我的对象又与它一起正确旋转。我尝试过很多不同的事情试图让它起作用但无济于事,所以任何帮助都会受到高度赞赏。

float bx;
float by;
int boxSizeX = 150;
int boxSizeY = 30;
boolean overBox = false;
boolean locked = false;
float xOffset = 0.0; 
float yOffset = 0.0; 
float angle;

void setup()
{
  size(800, 600);
  frameRate(45);
  bx = width/2.0;
  by = height/2.0;
}

void draw()
{ 
  background(0);

  pushMatrix();
  translate(400, 425);
  rotate(angle);
  rect(-25, -15, boxSizeX, boxSizeY);
  popMatrix();

  rect(  bx-25, by-15,  boxSizeX, boxSizeY);
  //if (mouseX > bx-boxSizeX && mouseX < bx+boxSizeX && mouseY > by-boxSizeY && mouseY <     by+boxSizeY)
  if( mouseX > bx-25 && mouseX < bx+25+boxSizeX && mouseY > by-15 && mouseY < by+15+boxSizeY) {
    overBox = true;  
    if(!locked) { 
      stroke(255); 
      fill(153);
    } 
  } else {
    stroke(153);
    fill(153);
    overBox = false;
  }
}

void mousePressed() 
{
  if(overBox) { 
    locked = true; 
    fill(255, 255, 255);
  } else {
    locked = false;
  }
  xOffset = mouseX-bx; 
  yOffset = mouseY-by; 
}

void mouseDragged() 
{
  if(locked) {
     bx = mouseX-xOffset; 
     by = mouseY-yOffset; 
     angle = atan2(mouseY - 400, mouseX - 400);
   }
}

1 个答案:

答案 0 :(得分:0)

我认为这就是你要找的东西。基本上,当你点击框时设置一个标志。如果拖动鼠标并且标志为true,则旋转。

int boxX, boxY;          // position of box
int boxRadius;           // width of box / 2
float boxAngle = 0.01;   // keep track of angle of rotation
boolean inBox = false;   // are we clicking in the box?

// have we clicked in the box?
void mousePressed() {
if (mouseX > boxX-boxRadius && mouseX < boxX+boxRadius && mouseY > boxY-boxRadius && mouseY < boxY+boxRadius) {
  inBox = true;
}

// stop behavior when we release the mouse
void mouseReleased() {
  inBox = false;
}

// rotate!
void mouseDragged() {
  if (inBox) {
    pushMatrix();
    translate(boxX, boxY);
    rotate(radians(boxAngle));
    fill(255,150,0);
    rect(0,0, boxRadius*2, boxRadius*2);
    popMatrix();

    // update the angle each frame
    boxAngle += 0.1;
  }
}