How to make my collision check with Intersect between rectangles to work?

独自空忆成欢 提交于 2019-12-06 16:59:04

问题


EDIT:here is the full code: https://dl.dropboxusercontent.com/u/65678182/assignment1.rar Any possible help is highly appreciated!


I am trying to make a copy of the breakout game, but I have problems with checking if two objects (the ball and paddle) intersects.

I have this method for collision detection for now:

public static void handleCollisions()
    {

        System.out.println(ball.getBounds());        // just to check that they                  
        System.out.println(paddle.getBounds());      //are there and moving correct

        if (ball.getBounds().intersects(paddle.getBounds()))
            {
        System.out.println("collision");
            }
    }

I'm pretty sure the getBounds works as they should since I get these outputs from the println: java.awt.Rectangle[x=393,y=788,width=14,height=14] java.awt.Rectangle[x=350,y=350,width=100,height=10]

getBounds code:
    public static Rectangle getBounds()
    {
        return new Rectangle(x, y, radius*2, radius*2);                     
    }

and I can see them moving at one point they are overlapping, but the method never detects it.

I'm pretty new to this so hopefully its just some stupid mistake somewhere, and any help is appreciated. I can post some more code if necessary, but would prefer to not.


回答1:


java.awt.Rectangle[x=393,y=788,width=14,height=14] 
java.awt.Rectangle[x=350,y=350,width=100,height=10]

As you can see the second rectangle's y/height 350/10 but the first's y=788

Obviously they have no intersection one is above another

UPDATE One more thing

public static Rectangle getBounds()
{
    return new Rectangle(x, y, radius*2, radius*2);                     
}

If x and y are the ball's center the code should be

public static Rectangle getBounds()
{
    return new Rectangle(x-radius, y-radius, radius*2, radius*2);                     
}


来源:https://stackoverflow.com/questions/22777498/how-to-make-my-collision-check-with-intersect-between-rectangles-to-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!