首页 \ 问答 \ Java编程,突破游戏球物理不符合预期(Java programming, breakout game ball physics not behaving as expected)

Java编程,突破游戏球物理不符合预期(Java programming, breakout game ball physics not behaving as expected)

我正在学习Java,书中有“Java的艺术与科学:计算机科学概论”。 其中一个练习程序是创建一个简单的Breakout游戏克隆。

我目前能够加载游戏,但我遇到了球物理问题。 我正在使用最简单的物理,并且无法理解为什么它不起作用。

当球击中墙壁时,它会正常弹跳,但是当它击中桨或砖时,它不会。 我在碰撞检测中使用相同的代码来改变我在墙壁上使用的方向。 检测到碰撞,我添加了一个println并在通过碰撞事件时观察了控制台,但方向改变没有发生。

package chapter10;

/* 
 * This program creates a clone of the classic Breakout Game,
 * where a player bounces a ball with a paddle to "break" bricks 
 * along the top of the screen.
 * 
 * Controls: Left: left button, Right: right button
 */

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.RepaintManager;
import javax.swing.Timer;

import acm.program.*;
import acm.graphics.*;

public class BreakoutClone extends GraphicsProgram {

/* components */
private GRect paddle;
private GRect brick;
private GOval ball;

/* static variables */

private static final double PADDLE_HEIGHT = 5;
private static final double BALL_SPEED = 2;
private static final double PADDLE_SPEED = 2;
private static final double ROWS_BRICKS = 6;
private static final double COLUMNS_BRICKS = 10;
private static final double TOP_GAP = 50;

/* variables */

private int numTurns = 3;
private double paddleWidth = 50;
private int dx = 2;
private int dy = 2;

public void init() {
    setSize(700, 600);

    paddle = new GRect(0, getHeight() - 30, paddleWidth, PADDLE_HEIGHT);
    paddle.setFilled(true);
    add(paddle);

    addBricks();

    ball = new GOval(getWidth() / 2, 175, 5, 5);
    ball.setFilled(true);
    add(ball);
}

public void run() {
    animateBall();
    // TODO animate paddle
}

public void addBricks() {
    double gap = 20;
    double brickWidth = getWidth() / COLUMNS_BRICKS;
    for (int r = 0; r < ROWS_BRICKS; r++) {
        for (int b = 0; b < COLUMNS_BRICKS; b++) {
            brick = new GRect(b * brickWidth, gap * r + TOP_GAP,
                    brickWidth, 10);
            brick.setFilled(true);
            add(brick);
        }
    }
}

public void endGame() {
    // TODO write end game method
}

public void animateBall() {

    while (numTurns > 0) {

        ball.move(dx, dy);
        pause(15);

        /* Look for Object Collision */
        GObject topRightObject = getElementAt(ball.getX() + 5, ball.getY());
        GObject topLeftObject = getElementAt(ball.getX(), ball.getY());
        GObject botRightObject = getElementAt(ball.getX() + 5,
                ball.getY() + 5);
        GObject botLeftObject = getElementAt(ball.getX(), ball.getY() + 5);

        /* Bounce off walls */

        if ((ball.getX() >= getWidth() - 5) || ball.getX() <= 0) {
            dx = -dx;
        }
        if (ball.getY() <= 0) {
            dy = -dy;
        }
        if ((ball.getY() >= getHeight() - 5)) {
            dy = -dy;
            // numTurns--;
            // if (numTurns == 0) {
            // endGame();
            // } else {
            // run();
            // }
        }

        /* Bounce off objects, remove bricks */

        if (topRightObject != null) {
            dy = -dy;
            hasCollided(topRightObject);
        }
        if (topLeftObject != null) {
            dy = -dy;
            hasCollided(topLeftObject);
        }
        if (botRightObject != null) {
            dy = -dy;
            hasCollided(botRightObject);
        }
        if (botLeftObject != null) {
            dy = -dy;
            hasCollided(botLeftObject);
        }
    }
}

private void hasCollided(GObject obj) {
    if (obj.equals(paddle)) {
        System.out.println("detecting paddle");

    } else {
        System.out.println("detecting brick");

        remove(obj);
    }
}
}

I am studying java with the book "The Art and Science of Java: An Introduction to Computer Science". One of the practice programs is to create a simple clone of the Breakout game.

I am currently able to load the game, but am having issues with the ball physics. I'm using the simplest physics possible, and can't see why it isn't working.

When the ball hits a wall, it bounces normally, but when it hits the paddle or a brick, it doesn't. I'm using the same code in the collision detection to change the direction that I used with the walls. The collisions are detected, I added a println and watched the console as it went through the collision events, but the direction change is not happening.

package chapter10;

/* 
 * This program creates a clone of the classic Breakout Game,
 * where a player bounces a ball with a paddle to "break" bricks 
 * along the top of the screen.
 * 
 * Controls: Left: left button, Right: right button
 */

import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.RepaintManager;
import javax.swing.Timer;

import acm.program.*;
import acm.graphics.*;

public class BreakoutClone extends GraphicsProgram {

/* components */
private GRect paddle;
private GRect brick;
private GOval ball;

/* static variables */

private static final double PADDLE_HEIGHT = 5;
private static final double BALL_SPEED = 2;
private static final double PADDLE_SPEED = 2;
private static final double ROWS_BRICKS = 6;
private static final double COLUMNS_BRICKS = 10;
private static final double TOP_GAP = 50;

/* variables */

private int numTurns = 3;
private double paddleWidth = 50;
private int dx = 2;
private int dy = 2;

public void init() {
    setSize(700, 600);

    paddle = new GRect(0, getHeight() - 30, paddleWidth, PADDLE_HEIGHT);
    paddle.setFilled(true);
    add(paddle);

    addBricks();

    ball = new GOval(getWidth() / 2, 175, 5, 5);
    ball.setFilled(true);
    add(ball);
}

public void run() {
    animateBall();
    // TODO animate paddle
}

public void addBricks() {
    double gap = 20;
    double brickWidth = getWidth() / COLUMNS_BRICKS;
    for (int r = 0; r < ROWS_BRICKS; r++) {
        for (int b = 0; b < COLUMNS_BRICKS; b++) {
            brick = new GRect(b * brickWidth, gap * r + TOP_GAP,
                    brickWidth, 10);
            brick.setFilled(true);
            add(brick);
        }
    }
}

public void endGame() {
    // TODO write end game method
}

public void animateBall() {

    while (numTurns > 0) {

        ball.move(dx, dy);
        pause(15);

        /* Look for Object Collision */
        GObject topRightObject = getElementAt(ball.getX() + 5, ball.getY());
        GObject topLeftObject = getElementAt(ball.getX(), ball.getY());
        GObject botRightObject = getElementAt(ball.getX() + 5,
                ball.getY() + 5);
        GObject botLeftObject = getElementAt(ball.getX(), ball.getY() + 5);

        /* Bounce off walls */

        if ((ball.getX() >= getWidth() - 5) || ball.getX() <= 0) {
            dx = -dx;
        }
        if (ball.getY() <= 0) {
            dy = -dy;
        }
        if ((ball.getY() >= getHeight() - 5)) {
            dy = -dy;
            // numTurns--;
            // if (numTurns == 0) {
            // endGame();
            // } else {
            // run();
            // }
        }

        /* Bounce off objects, remove bricks */

        if (topRightObject != null) {
            dy = -dy;
            hasCollided(topRightObject);
        }
        if (topLeftObject != null) {
            dy = -dy;
            hasCollided(topLeftObject);
        }
        if (botRightObject != null) {
            dy = -dy;
            hasCollided(botRightObject);
        }
        if (botLeftObject != null) {
            dy = -dy;
            hasCollided(botLeftObject);
        }
    }
}

private void hasCollided(GObject obj) {
    if (obj.equals(paddle)) {
        System.out.println("detecting paddle");

    } else {
        System.out.println("detecting brick");

        remove(obj);
    }
}
}

原文:https://stackoverflow.com/questions/28397996
更新时间:2022-11-23 19:11

最满意答案

选择所需的范围并输入以下ex命令:

:'<,'>s/\s*\\$/\=repeat(' ', 80-col('.')).'\'

用行重尾处的空格和\替换表达式,该表达式在第80列之前重复一个空格,然后附加一个\字符。 如果您的行超过80个字符,它将附加0个空格,这可能不是您想要的,在这种情况下将80更改为79并为字符串添加空格: ' \'


select the range you want and enter the following ex command:

:'<,'>s/\s*\\$/\=repeat(' ', 80-col('.')).'\'

Which substitutes the whitespace and \ at the end of the line with an expression which repeats a space up until column 80 and then appends a \ character. It'll append 0 spaces if your line is > 80 characters, which may not be what you want, in which case change the 80 to 79 and add a space to the string: ' \'

相关问答

更多

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)