简体   繁体   English

使用.intersection的矩形和圆碰撞Java

[英]Rectangle and Circle Collision Java using .intersection

I am making a breakout game for a school project. 我正在为学校项目制作突破游戏。 The only problem I am running into is the Ball Bouncing when the Ball and Bricks collide. 我遇到的唯一问题是当球和砖块碰撞时的球弹跳。 I used ball1.getEllipse().intersects(b.getRectangle()) allowing me to figure out when it is colliding and delete the brick. 我使用了ball1.getEllipse()。intersects(b.getRectangle()),让我可以确定何时发生碰撞并删除积木。 The bouncing chances depending on the side it collided with. 弹跳的机会取决于它碰到的那一侧。 This is the main problem. 这是主要问题。 The .intersect piece does not show me which side the brick gets hit by. .intersect件没有告诉我砖被打到哪一侧。 I need this to know whether to change the x or y speed. 我需要知道是否更改x或y速度。 If anyone has any idea on how to figure this out, please leave your input (I have been trying to think of a solution for 5 hours, I gave up) 如果有人对如何解决这个问题有任何想法,请留下您的意见(我已经尝试了5个小时的解决方案,我放弃了)

 public void collision(int i) {

    for (Block b : blocks) {
        if (ball1.getEllipse().intersects(b.getRectangle())) {
            if (!b.isDestroyed()) {
                b.destroy();
                blockCount-=1;
                ball1.brickBounce();`public void collision(int i) {

From what I understand from your question, you want to know which side of the rectangle the ball is hitting. 根据您对问题的了解,您想知道球正在击中矩形的哪一侧。 A simple way of doing this would be to take the position of the ball and the position of the rectangle and compare the two. 一种简单的方法是将球的位置和矩形的位置进行比较。 If the ball's x position is less than the rectangles x position - half its width(to get the x position of the bound), then the ball hit on the left side. 如果球的x位置小于矩形的x位置-宽度的一半(以获取边界的x位置),则球在左侧命中。 You can then do the opposite for the right side. 然后,您可以对右侧执行相反的操作。 Checking if it hit on top or bottom is similar just with the y positions and the rectangle's height. 仅在y位置和矩形的高度上检查它是否在顶部或底部命中。 Do note that I'm assuming the x and y position of each shape is the center, if not only minor adjustments should have to be made to get the same result as if it were the center. 请注意,我假设每个形状的x和y位置都为中心,如果不仅需要进行微小的调整以使其获得与中心相同的结果,就可以了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM