java - 弹跳球不会停在边界 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
}
}
解决方案
好的,这是工作代码: 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)。这就是为什么我有很多问题。您始终应该检查起点是否适合半径。
推荐阅读
- maven - Maven Surefire 不会重新运行失败的 testng 测试,我的配置有什么问题?
- java - 如何调整行并将其移动到右侧
- java - 一旦 EditText 获得焦点,如何让我的 AlertDialog 出现?
- f# - F# 元组列表
- javascript - 如何使用 GraalVM 创建 node.js 原生镜像
- python - Kivy 如何在弹出窗口中正确使用 FileBrowser
- javascript - 迭代 knockout.js 可观察对象的 javascript 属性以创建订阅
- ruby-on-rails - 在 rspec 测试运行之前清除 sprockets 缓存
- visual-studio-code - 如何以编程方式在 VS Code 中显示 CompletionList?
- c++ - 不同范围内的 C++ 对象引用