java - 我的碰撞检测不适用于 Java 图形
问题描述
int border=30;
boolean balldown=true;
boolean ballright=true;
int bounce=0;
public void moveBall(){
if (balldown==true){
//y++;
rect3.b++;
}
if (balldown==false){
y--;
rect3.b--;
}
//y==getHeight()-border
if(rect3.b==getHeight()-border){
balldown=false;
bounce++;
}
//y==0
if(rect3.b==0){
balldown=true;
bounce++;
}
if (ballright==true){
x++;
rect3.a++;
}
if (ballright==false){
x--;
rect3.a--;
}
//x==getWidth
if(colision==true){
ballright=false;
bounce++;
}
colision=false;
//x==0
//rect3.bounds2()==rect1.bounds()
if(colision==true){
ballright=true;
bounce++;
}
}
/* if(rect3.a==getWidth()){
ballright=false;
}
if(rect3.a==0){
ballright=true;
}*/
}
// int a=0;
// int b=0;
//int width=30;
// int height=200;
rect rect1;
rect rect2;
rect rect3;
Timer time;
boolean colision=false;
public Pong() {
rect1 = new rect(0,0);
rect2 = new rect(977,0);
rect3=new rect(40,40);
time=new Timer(5,this);
time.start();
}
public class rect{
int a,b;
public rect(int startA, int startB){
a=startA;
b=startB;
}
public Rectangle bounds(){
return (new Rectangle(a,b,30,200));
}
public Rectangle bounds2(){
return (new Rectangle(a,b,30,30));
}
}
@Override
public void paint(Graphics g){
super.paint(g);
Graphics2D g2d=(Graphics2D) g;
g.setColor(Color.BLACK);
g.fillRect(0, 0, 1080, 760);
g2d.setColor(Color.WHITE);
// g.fillOval(x, y, 30, 30);
g2d.fillRect(rect3.a, rect3.b, 30, 30);
g2d.setColor(Color.WHITE);
g2d.fillRect(rect1.a, rect1.b, 30, 200);
g2d.setColor(Color.WHITE);
g2d.fillRect(rect2.a, rect2.b, 30, 200);
g2d.fillRect(520, 0, 10, 760);
if (colision==true)
g.setFont(new Font("TimesRoman", Font.PLAIN, 20));
g.drawString("Colision",350, 50);
g.setFont(new Font("TimesRoman", Font.PLAIN, 20));
g.setColor(Color.WHITE);
g.drawString("BOUNCES: "+bounce, 40, 20);
}
public void colision(){
Rectangle rectangle1=rect1.bounds();
Rectangle rectangle2=rect2.bounds();
Rectangle rectangle3=rect3.bounds2();
if(rectangle3.intersects(rectangle1))
colision=true;
else
colision=false;
if(rectangle3.intersects(rectangle2))
colision=true;
else
colision=false;
}
@Override
public void actionPerformed(ActionEvent e){
moveBall();
colision();
repaint();
所以基本上我的 if 语句使用 intersects 永远不会在我的球击中侧面的矩形时返回 true。同样在我的 moveball 方法中,只要这些边界相遇,它就应该在另一个方向“反弹”,但它不起作用,甚至只是通过低谷而没有碰撞检测。我执行错了吗?当我检查 system.out.print 时,它会以每秒 2 次甚至更快的速度不断返回消息。我是一个 java 初学者,不要因为明显的错误和糟糕的结构而对我大喊大叫。谢谢
解决方案
推荐阅读
- c - 64 位长整型参数
- amazon-web-services - AWS lambda 用于从 s3 到 rds 的自动还原
- sql - 尝试在一行中显示从不同条目存储的 REPLACED 和 ORIGINAL 值(在不同列下)
- python - Seaborn - 通过直方图中的一个因子修改 y 轴
- f# - 从擦除类型引用生成的类型
- json - 如何在 httpie 中发送包含引号的 POST 请求?
- scheme - 检查 K 组合器的绑定变量失败
- sql - 如何在数据库项目中的部署后脚本和部署前脚本之间共享项目版本号
- java - SpringBoot 日志记录 - 每个日志语句中的堆栈跟踪
- java - 没有出现通知 - 如何解决?