Java 砖块碰撞 [关闭]

2023-12-03

我一直在开发一款 Breakout 游戏,除了砖块碰撞之外,几乎所有的事情都完成了。球在墙壁和桨上弹跳得很好,但当它碰到砖块时,它会直接穿过它们。我很确定问题出在主类的 checkBrick() 部分,但不知道该怎么办。

主要类别:

import java.awt.*;
import java.awt.event.KeyEvent;
import java.applet.*;
import java.util.Random;
import javax.swing.JOptionPane;

public class Breakout extends Applet implements Runnable {
    Ball ball = new Ball();
    Paddle paddle = new Paddle(135, 375);
    Brick[] brick = new Brick[50];
    private int bX[] = new int[50];
    private int bY[] = new int[50];
    private int bW[] = new int[50];
    private int bH[] = new int[50];
    Thread t;
    Random trajectory = new Random();
    boolean lose;
    Image buffer = null;

    // The life cycle of the Applet
    // Sets up window
    public void init() {
        setSize(377, 500);
        buffer = createImage(377, 500);
        // setBackground(Color.black);
        System.out.println("init()");
    }

    public void start() {
        if (t == null) {
            t = new Thread(this);
            t.start();
        }
        System.out.println("start()");
    }

    public void run() {
        System.out.println("run()");
        Thread.currentThread().setPriority(Thread.MIN_PRIORITY);

        while (!lose) {
            ball.move();
            paddle.move();
            checkWall();
            checkPaddle();
            checkBrick();
            ball.move();

            repaint();

            try {
                Thread.sleep(30);
            } catch (InterruptedException ex) {
            }
            Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
        }

        JOptionPane.showMessageDialog(null, "Game Over");
        System.out.println("Termintated");
        System.exit(0);
    }

    public void stop() {
        System.out.println("stop()");
    }

    public void destroy() {
        System.out.println("destroy()");
    }

    public void paint(Graphics g) {
        Graphics screen = null;
        screen = g;
        g = buffer.getGraphics();

        g.setColor(Color.black);
        g.fillRect(0, 0, 377, 500);
        createBricks(g);
        createPaddle(g);
        createBall(g);

        screen.drawImage(buffer, 0, 0, this);
    }

    public void update(Graphics g) {
        paint(g);
    }

    private void createBricks(Graphics g) {
        int brickIndex = 0;
        int brickX = 15, brickY = 160;
        int brickW = 30, brickH = 10;
        for (int i = 0; i <= 4; i++) {
            brickX = 15;
            brickY -= 20;

            for (int n = 0; n < 10; n++) {
                brick[brickIndex] = new Brick();
                brick[brickIndex].setBounds(brickX, brickY, brickW, brickH);
                bX[brickIndex] = brick[brickIndex].x();
                bY[brickIndex] = brick[brickIndex].y();
                bW[brickIndex] = brick[brickIndex].w();
                bH[brickIndex] = brick[brickIndex].h();
                brick[brickIndex].setColor(i);
                brick[brickIndex].paint(g);
                brickIndex++;
                brickX += 35;
            }
        }

    }

    private void createPaddle(Graphics g) {
        paddle.paint(g);

    }

    private void createBall(Graphics g) {
        ball.paint(g);
    }

    private void checkWall() {
        // If ball hits right wall it will bounce
        if ((ball.getX() + ball.getR()) >= 380) {
            ball.setVX(trajectory.nextInt(2) + -3);
        }

        // If ball hits left wall it will bounce
        if ((ball.getX() - ball.getR()) < -10) {
            ball.setVX(trajectory.nextInt(4) + 1);
        }

        // If ball hits ceiling it will bounce
        if ((ball.getY() + ball.getR()) < 12)
            ball.setVY(trajectory.nextInt(5) + 1);

        // If ball goes through floor it will subtract a life
        if ((ball.getY() + ball.getR()) > 515)
            lose = true;

    }

    private void checkBrick() {
        for (int i = 0; i < 50; i++) {
            int tempX, tempY, tempW, tempH;
            tempX = bX[i];
            tempY = bY[i];
            tempW = bW[i];
            tempH = bH[i];

            if ((ball.getX() + ball.getR()) < (tempX + tempW)
                    && (ball.getX() + ball.getR()) >= tempX) {
                if ((ball.getY() + ball.getR()) > (tempY + tempH)
                        && (ball.getY() + ball.getR()) <= tempY) {
                    System.out.println("Brick " + i + " has been hit.");
                }
            }
        }
    }

    private void checkPaddle() {
        // Check for paddle
        if ((ball.getX() + ball.getR()) < (paddle.getX() + 100)
                && (ball.getX() + ball.getR()) >= paddle.getX() + 5) {
            if ((ball.getY() + ball.getR()) > (paddle.getY() - 5)
                    && (ball.getY() + ball.getR()) <= (paddle.getY() + 5)) {
                ball.setVX((trajectory.nextInt(7) + -2) + 1);
                ball.setVY(trajectory.nextInt(1) + -3);
            }
        }
    }

    // Key Detectors
    public boolean keyDown(Event e, int key) {
        if (key == Event.RIGHT) {
            paddle.setVX(0);
            if ((paddle.getX() + 100) < 377)
                paddle.setVX(10);
        }
        if (key == Event.LEFT) {
            paddle.setVX(0);
            if (paddle.getX() > 0)
                paddle.setVX(-10);
        }

        return true;
    }

    // To make sure it doesn't just keep moving one way
    public boolean keyUp(Event e, int key) {
        paddle.setVX(0);
        return true;
    }
}

球类:

import java.awt.Color;
import java.awt.Graphics;
import java.util.Random;

public class Ball 
{
    private int x, y; //Position
    private int vx, vy; //Velocity
    private int r; //radius

    //constructor
    public Ball()
    {
        x = 177;
        y = 315;
        vx = 0;
        vy = 5;
        r = 15;
    }

    public void paint(Graphics g)
    {
        g.setColor(Color.white);
        g.fillOval(x, y, r, r);

    }

    //returns the x of origin 
    public int getX()
    {
        return x;
    }

    //returns the y of origin
    public int getY()
    {
        return y;
    }
    public int getVX()
    {
        return vx;
    }

    //returns the y of origin
    public int getVY()
    {
        return vy;
    }

    //returns the radius r of the ball
    public int getR()
    {
        return r;
    }

    //sets the velocity of x to a different value
    public void setVX(int vx)
    {
        this.vx = vx;
    }

    //sets the velocity of y to a different value
    public void setVY(int vy)
    {
        this.vy = vy;
    }

    //sets the x value
    public void setX(int x)
    {
        this.x = x;
    }

    //sets the y value
    public void setY(int y)
    {
        this.y = y;
    }

    //starts making the ball move by changing its coords
    public void move()
    {
        x+= vx;
        y+= vy;
    }

}

桨类:

import java.awt.Color;
import java.awt.Graphics;

public class Paddle {

    // declares variables for x and y coordinates
    int x, y;
    //The velocity of to move paddle
    int vx;

    // constructor that takes in x and y coordinates for paddle
    public Paddle(int x, int y) 
    {
        this.x = x;
        this.y = y;
    }

    public void paint(Graphics g) 
    {
        // paints paddle
        g.setColor(Color.WHITE);
        g.fillRect(x, y, 100, 15);
        g.setColor(Color.GREEN);
        g.drawRect(x, y, 100, 15);
    }

    // gets x coordinate of paddle
    public int getX() {
        return x;
    }

    // sets x coordinate of paddle
    public void setX(int x) {
        this.x = x;
    }

    // gets y coordinate of paddle
    public int getY() {
        return y;
    }

    // sets y coordinate of paddle
    public void setY(int y) {
        this.y = y;
    }

    public void setVX(int vx)
    {
        this.vx = vx;
    }
    //Moves the paddle
    public void move()
    {
        x+=vx;
    }
}

砖类:

import java.awt.Color;
import java.awt.Graphics;


public class Brick 
{
    private Color color =(Color.cyan);
    private int x, y, w, h;

    public Brick()
    {
        //Garbage values that are there just for declaration
        x = 0;
        y = 0;
        w = 10;
        h = 10;
    }

    //Sets color for the brick
    public void setColor(int paintC)
    {
        switch(paintC)
        {
            case 0:
                color = (Color.magenta);
                break;
            case 1:
                color = (Color.blue);
                break;
            case 2:
                color = (Color.yellow);
                break;
            case 3:
                color = (Color.orange);
                break;
            default:
                color = (Color.red);
                break;
        }
    }

    //Sets the location then size of the brick
    public void setBounds(int x, int y, int w, int h)
    {
        this.x = x;
        this.y = y;
        this.w = w;
        this.h = h;
    }

    //returns x value
    public int x()
    {
        return this.x;
    }

    //returns y value
    public int y()
    {
        return this.y;
    }

    //returns width value
    public int w()
    {
        return this.w;
    }

    //returns height value
    public int h()
    {
        return this.h;
    }


    //Sets x for the brick
    public void setX(int x)
    {
        this.x = x;
    }

    //Sets y for the brick
    public void setY(int y)
    {
        this.y = y;
    }

    public void setW(int w)
    {
        this.w = w;
    }

    public void setH(int h)
    {
        this.h = h;
    }

    public void paint(Graphics g)
    {
        g.setColor(color);
        g.fillRect(x, y, w, h);
        g.setColor(Color.green);
        g.drawRect(x, y, w, h);
    }
}

我已经开始运行你的代码,坦率地说,我不想费心去弄清楚你的逻辑,但我相信你想要推断的是砖块是否“包含”球,而不是球是否与砖头。

你并不关心球或砖块有多少相交,只要它们相交......例如......

private void checkBrick() {

    int tx = ball.getX();
    int ty = ball.getY();
    int tw = ball.getR();
    int th = ball.getR();

    tw += tx;
    th += ty;

    for (int i = 0; i < 50; i++) {
        int tempX, tempY, tempW, tempH;
        tempX = bX[i];
        tempY = bY[i];
        tempW = bW[i];
        tempH = bH[i];

        int rw = tempW + tempX;
        int rh = tempH + tempY;

        //     overflow || intersect
        if ((rw < tempX || rw > tx) &&
            (rh < tempY || rh > ty) &&
               (tw < tx || tw > tempX) &&
               (th < ty || th > tempY)) {
            System.out.println("Hit");
        }
    }
}

现在,我从Rectangle#intersects

基本上,如果您使用 2D 图形 API 中的几何类,您可以将其减少到...

private void checkBrick() {

    Rectangle b = new Rectangle(ball.getX(), ball.getY(), ball.getR(), ball.getR());

    for (int i = 0; i < 50; i++) {
        int tempX, tempY, tempW, tempH;
        tempX = bX[i];
        tempY = bY[i];
        tempW = bW[i];
        tempH = bH[i];

        Rectangle brick = new Rectangle(tempX, tempY, tempW, tempH);

        System.out.println("brick = " + brick);
        if (b.intersects(brick)) {
            System.out.println("Break");
        }
    }
}

是的,我确实运行了你的代码

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Java 砖块碰撞 [关闭] 的相关文章

随机推荐

  • 如何将复数的虚部设置为零?

    我需要检查虚部是否非常小 如果是 则将其设置为零 以便消除一些浮点错误 这些错误会导致在应该为零的情况下产生非常小的非零虚部 我的代码如下 kz2 SQRT n2 2 0 PI eta 2 kxarray p 2 kz1 SQRT n1 2
  • 使用 CSS sprites 在表单元素上定位背景图像

    我正在尝试使用放大镜作为输入元素的背景 放大镜图标是 CSS 精灵的一部分 如下所示 为了定位它 我使用了这些属性 search form input type text background url images icons png no
  • MATLAB:任意数量的元胞数组的组合

    MATLAB 中是否有命令或单行策略可以返回以下组件的所有组合n元胞数组 采取n一次 我想要完成的一个例子 A a1 a2 B b1 b2 b3 C combinations A B C a1 b1 a1 b2 a1 b3 a2 b1 a2
  • 如何在 JTable 之后添加 JButton

    我有一个 JTable 其中包含一些像这样的 SSCCE 数据 import java awt import java awt event import javax swing import java io import javax swi
  • Microsoft Graph API BETA - 返回加密/散列的 userPrincipalName 的报告

    当调用报告端点之一时 例如https graph microsoft com beta reports getTeamsUserActivityUserDetail 期间 D7 format application json 对于我们的租户
  • 如何在Python中将加权边列表转换为邻接矩阵?

    数据存在于 Excel 文件中 第一列代表第一个节点 第二列代表第二个节点 第三列包含权重 节点是字符串 Eg 苹果香蕉 65橙苹果 32 首先要做的是导入 Excel 文件 最直接的方法是使用pandas import pandas da
  • 如何使用 Chromedriver 和 Selenium Python 在 Instagram 登录页面中找到用户名和密码字段

    这是经过检查的源代码 input aria label Phone number username or email aria required true autocapitalize off autocorrect off maxleng
  • Android 自定义溢出菜单(没有操作栏和菜单按钮)

    在我的应用程序中 我制作了自己的操作栏 并且效果很好 不过 我想在没有菜单按钮的 ICS 设备上使用溢出按钮的行为 有没有办法在 ICS 中实现与操作栏分开的自定义溢出按钮 Thanks userSeven7s 主要有ListPopupWi
  • 名称查找中的重载解析/歧义(哪一个)

    7 3 3 14 C 03 struct A int x struct B A struct C A using A x int x int struct D B C using C x int x double int f D d ret
  • 如何在 php 中创建存档列表?

    我正在创建我的公司博客 想知道如何创建一个存档页面 读者可以在其中单击月份 年份并显示该时间段的所有博客文章 这些天我经常在博客上看到这个 并且想知道我自己如何创建它 它看起来像这样 2012年7月 2012年6月 2012年3月 显然 我
  • Objective-C:在 iPhone 上访问 REST API 的最佳方式

    已经为此苦苦挣扎了一段时间 我正在尝试访问 iPhone 上的 REST api 并遇到了可以帮助我的 ASIHTTP 框架 所以我做了类似的事情 call sites so we can confirm username and pass
  • 从点数组平滑二维线

    当用户绘图时 每次输入事件触发时我都会捕获他们输入的位置 然后在每个点之间绘制直线 不幸的是 这会产生非常锯齿状的外观 并且情况会变得更糟 具体取决于用户移动输入的速度相对于输入事件触发的速度 我想要的是一个函数 它接受一个点数组并返回一个
  • 如何在三元运算符中使用 ASP.NET Eval() 函数?

    我希望评估数据集中的两个字符串 以使用三元运算符来识别类描述 运行此代码时 我继续收到编译器错误 指出 需要表达式 我认为这与字符串的比较有关 但我尝试过其他比较运算符 但似乎无法让它工作
  • 自动删除 EditText 任何文本的前导空格?

    描述 我正在开发一个应用程序 其中有注册页面 在注册页面内 我通过获取用户的全名和手机号码进行注册 Problem 在编辑文本中获取用户的全名时 有时用户会在输入他 她的名字之前按空格键 我需要您在输入任何文本之前禁用空格键 白人用户开始输
  • 使用 Visual Studio 2008 中的设计器将逗号分隔列表作为参数传递给 db2 查询的 IN 子句

    我想将逗号分隔的值列表作为参数传递给我正在使用 Visual Studio 2008 中的设计器 基于我正在经历的一些强类型 DAL 教程 构建的查询 该查询针对 DB2 数据库 这就是我想做的 从客户所在的价格中选择 它工作得很好 我在
  • 调用结果未使用

    在第二条评论的正下方 我收到一条错误 调用 taskForDeleteMethod 的结果未使用 为什么当我在调用后的闭包中使用结果和错误时会出现这种情况 func deleteSession completionHandlerForDel
  • Java 重写私有函数不显示多态行为

    public class Shape final private void print System out println in class Shape public static void main String args Shape
  • 如何知道 onCreateView 函数中哪个选项卡处于活动状态?

    我如何知道我的哪个选项卡处于活动状态 public View onCreateView LayoutInflater inflater ViewGroup容器 Bundle savingInstanceState 函数 以下代码仅适用于首次
  • 调用 SwingWorker.get( ) 时防止 GUI 冻结

    我有一个程序 我正在加载文件 同时显示一个窗口以通知用户正在加载文件 我决定创建一个 FileLoader 类 它是一个 SwingWorker 它实际上处理加载文件 还有一个 ProgressWindow 它实现 PropertyChan
  • Java 砖块碰撞 [关闭]

    Closed 这个问题需要多问focused 目前不接受答案 我一直在开发一款 Breakout 游戏 除了砖块碰撞之外 几乎所有的事情都完成了 球在墙壁和桨上弹跳得很好 但当它碰到砖块时 它会直接穿过它们 我很确定问题出在主类的 chec