java - 当我单击鼠标时,我试图让我的三角形自己重绘,但是当我单击鼠标时它们只会相乘
问题描述
当我运行这个程序时,绿色三角形出现在我点击的地方,而不是我希望它重新定位到一个随机的地方并删除原来的绿色三角形
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);
}
}
解决方案
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.
推荐阅读
- python - 侧边栏菜单应基于基于角色的登录 django 加载
- asp.net-mvc - 从登录 Asp.net 核心中排除自定义异常类
- kubernetes - 我的 pod 处于 Container Creating 状态,显示 TLS 握手超时
- ckeditor - ckeditor4 CDN 添加额外的插件“模板”
- python - 从以其他元素为条件的元组中删除元素
- node.js - 使用 Promise 改进 mongodb 请求的代码
- listview - 将所选图像添加到水平 listView
- android - 离子 4 和谷歌本机登录的错误代码 10
- java - 从 JWT 令牌中删除角色信息
- java - 如何将解析的 JSON 保存到 mongodb 中?