首页 > 解决方案 > 为什么这些物体在使用“相交”时不会碰撞

问题描述

我制作了 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();
                }
            }

标签: java

解决方案


推荐阅读