首页 > 解决方案 > 弹跳球不会停在边界 JAVA

问题描述

我的弹跳球旨在在 200x200 窗口的边界之间弹跳。当他触及右侧和底部边界时,我设法让他停下来并改变方向。但是当他到达顶部和左侧边界时,一个 1/4 的球穿过边界,然后它才改变方向。

我不知道为什么会这样,我的意思是每个边框的代码行都是一样的。对于相同的代码,它怎么会以不同的方式工作呢?

我在网上浏览了很多关于这个主题的代码,并尝试了每一个解决方案或代码,它仍然保持不变。

谢谢。

 public Point applyToPoint(Point p) {
        return new Point(p.getX() + dx, p.getY() + dy);
    }

    public void moveOneStep(int width, int height) {
    if (this.center.getX() + this.getVelocity().dx + r > width) {
        this.setVelocity(-(this.getVelocity().dx), this.getVelocity().dy);
    }
    if (this.center.getX() + this.getVelocity().dx < 0) {
        this.setVelocity(-(this.getVelocity().dx), this.getVelocity().dy);
    }
    if (this.center.getY() + this.getVelocity().dy + r > height) {
        this.setVelocity(this.getVelocity().dx, -(this.getVelocity().dy));
    }
    if (this.center.getY() + this.getVelocity().dy < 0) {
        this.setVelocity(this.getVelocity().dx, -(this.getVelocity().dy));
    }
    moveOneStep();
}

public void moveOneStep() {
    this.center = this.getVelocity().applyToPoint(this.center);
}

r = 球的半径。

"this.center" = 球的中心点。

左边框小球截图:

图像

 import biuoop.DrawSurface;
import biuoop.GUI;
import biuoop.Sleeper;

public class BouncingBallAnimation {

    static private void drawAnimation(Point start, double dx, double dy) {
        GUI gui = new GUI("BouncingBall",200,200);
        Sleeper sleeper = new Sleeper();
        Ball ball = new Ball(new Point(start.getX(), start.getY()), 30, java.awt.Color.BLACK);
        ball.setVelocity(dx, dy);
        while (true) {
            DrawSurface d = gui.getDrawSurface();
            ball.moveOneStep(d.getHeight(),d.getWidth());
            ball.drawOn(d);
            gui.show(d);
            sleeper.sleepFor(50);  // wait for 50 milliseconds.
        }
    }
    public static void main(String[] args) {
        drawAnimation(new Point(20,33),6,6); //just a random input that I decided
    }
}

标签: javaanimationgeometryborderbounce

解决方案


好的,这是工作代码: public void moveOneStep(int startX, int height, int startY, int width) {

    if (this.center.getX() + this.getVelocity().dx + r >= width) {
        this.setVelocity(-1 * (this.getVelocity().dx), this.getVelocity().dy);
    }
    if (this.center.getX() + this.getVelocity().dx - r <= startX) {
        this.setVelocity(-1 * (this.getVelocity().dx), this.getVelocity().dy);
    }
    if (this.center.getY() + this.getVelocity().dy + r >= height) {
        this.setVelocity(this.getVelocity().dx, -1 * (this.getVelocity().dy));
    }
    if (this.center.getY() + this.getVelocity().dy - r <= startY) {
        this.setVelocity(this.getVelocity().dx, -1 * (this.getVelocity().dy));
    }
    moveOneStep();
}

问题不是代码,而是我输入检查圆圈的起点。如果半径是 30,你不能给圆的起始中心点让我们说 (20,50)。为什么?因为那样圆从一开始就出界了,因为他的起点中心点是20,50,半径是30,这意味着他的左半径将达到(-10, 50)。这就是为什么我有很多问题。您始终应该检查起点是否适合半径。


推荐阅读