首页 > 解决方案 > 当我单击鼠标时,我试图让我的三角形自己重绘,但是当我单击鼠标时它们只会相乘

问题描述

当我运行这个程序时,绿色三角形出现在我点击的地方,而不是我希望它重新定位到一个随机的地方并删除原来的绿色三角形


float x;

void setup()
{
  size (800, 600);
  background(29, 154, 178);
  x=random(width);
    frameRate(30);
}

void draw()
{
  noStroke();

  fill(91, 180, 118 );
  triangle(x, 20, 0, height, width, height);

  fill(82, 45, 80);
  triangle(width/2-200, 120, 0, height, width, height);

  fill(82, 45, 60);
  triangle(width/2+150, 220, 0, height, width, height);

  fill(82, 45, 28);
  triangle(width/2-100, 320, 0, height, width, height);
  fill(243, 245, 158);
  rect(0, 525, 800, 100);
  
  if(mousePressed == true)
  {
    x=random(width);
  }
}

标签: javaprocessing

解决方案


Then add noLoop() in your setup so you're not drawing the same thing 60 times a second, and use mouse click handling instead, with a redraw call so you only draw when there is something new to draw:

float x, y, triangleSideLength;

void setup() {
  size(300,300);
  noLoop();
  triangleSideLength = 30; // or whatever value it needs to be of course
}

void draw() {
  x = random(0, width - triangleSideLength);
  y = random(0, height - triangleSideLength);
  drawTriangleAt(x, y);
}

void drawTriangleAt(float x, float y) { 
  //...triangle drawing code here...
}

void mouseClicked() {
  redraw();
}

Also note that you usually want to constrain your x/y coordinates so that a triangle will always "fit on the screen" instead of getting an x/y coordinate that happens to have x=width and now your triangle is basically 100% out of view.


推荐阅读