java - 为什么这些物体在使用“相交”时不会碰撞
问题描述
我制作了 2 个对象(1. triangle (java.awt.polygon) 和 2. rectangle(java.awt.rectangle)),并通过 TIMER 移动了这些对象。我的目标是让这两个物体相互碰撞并反弹回来。问题是为什么当我使用 (..if(intersect..) 部分时它们没有碰撞和反弹。编译器(cmd) 遇到错误说[“没有找到适合相交的方法(Polygon)”]。
我觉得很奇怪,因为在此之前,当我创建 2 个矩形(使用 java.awt.Rectangle)并使用 (..if(intersects)...) 时,它工作得很好。这两个矩形触摸并相互反弹。我需要回答这个问题,错误是什么意思?下面是代码的一部分谢谢。
public void paintComponent(Graphics g) {
Graphics2D g2d = (Graphics2D) g;
super.paintComponent(g);
//1
triangle1 = new Polygon(new int[]{x1, x2, x3},
new int[]{200, 100, 200}, 3);
g2d.setColor(Color.RED);
g2d.fill(triangle1);
//2
r1 = new Rectangle(x, 100, 200, 100);
g2d.setColor(Color. BLUE);
g2d.fill(r1);
}
public void actionPerformed(ActionEvent e) {
if(x < 0 || x + r1.getWidth() > this.getWidth()) {
velx = -velx;
}
if(x1 < 0 || x3 > this.getWidth()) {
velx1 = -velx1;
velx3 = -velx3;
velx2 = -velx2;
}
// below code not working
if(r1.intersects(triangle1)) {
velx = -velx;
velx1 = -velx1;
velx3 = -velx3;
velx2 = -velx2;
}
x += velx;
x1 += velx1;
x2 += velx2;
x3 += velx3;
repaint();
}
}
解决方案
推荐阅读
- github - 如何将 GitHub Actions 与多个存储库一起使用并部署到 GitHub Pages?
- c# - WaitForSeconds有更好的方法吗?
- javascript - jQuery UI 对话框去除表单属性和非表单元素
- javascript - 如何在 settimeout 内解析异步函数
- laravel - laravel:今天使用碳检查用户今天在 laravel 中收到的电子邮件
- sql - 这个 WHERE IN 子查询的哪一部分是错误的?它不产生任何输出
- sql - 子查询中的描述顺序
- c++ - 如何使用递归打印修改后的星号三角形图案?
- sql - 如何从shell提示符将oracle sql脚本文件的参数传递给sqlplus?
- azureservicebus - 将 SAS 令牌与 Azure ServiceBus 一起使用