java - 球到矩形碰撞
问题描述
你好我正在用java制作一个需要从球碰撞到矩形的游戏。
pos.x = 球的 x 值
pos.y = 球的 y 值
vel.x = x 球的速度
vel.y = y 球的速度
sh = 球的高度
sw = 球的宽度
W = 矩形的宽度
H = 矩形的高度
到目前为止,我有:
boolean insideRect = pos.x >= X && pos.x <= X+W && pos.y >= Y && pos.y <= Y+H;
if(insideRect){
if(pos.y + sh/2 >= H){
vel.y = (-1*vel.y)*gravity;
vel.x *= .6;
if(pos.y < Y+H/2){
pos.y = Y;
} else{
pos.y = Y+H;
}
}
if(pos.x + sw/2 > W){
vel.x = -1*vel.x;
}
}
然而,这只是说它是否击中了矩形的左侧或右侧,以及它是否击中了顶部或底部。
因此,如果您在 if 语句下打印输出将是:(左,上),(右,下),(左,下),(右,上)
所以问题是,要让它工作,我只能有一个,左、右、上或下。
如果我有两个,那么它会认为它既撞到天花板又撞到了右边的墙上,并且有两个视觉输出。
我该如何解决这个问题?
解决方案
/**
* checks to see if the obstacles and balls collide.
* Utilizes bounding boxes for obstacles and coordinates for ball:
* + = Obstacle
* ballTop
* : :
* : :
*ballLeft : : ballRight
* : :
* : :
* ballBottom
*
* ____
* |+++|
* |+++|
* |+++|
* ----
* @param ball
* @param rect
* @return boolean
*/
public boolean intersects(Ball ball, Obstacle rect){
double r = ball.getRadius();
double rectTop = rect.y;
double rectLeft = rect.x;
double rectRight = rect.x + rect.width;
double rectBottom = rect.y + rect.height;
double ballTop = ball.y - r;
double ballLeft = ball.x - r;
double ballRight = ball.x + r;
double ballBottom = ball.y + r;
//NO COLLISIONS PRESENT
if(ballRight < rectLeft){
return false;
}
if(ballTop > rectBottom){
return false;
}
if(ballBottom < rectTop){
return false;
}
if(ballLeft > rectRight){
return false;
}
//HAS TO BE A COLLISION
return true;
}
//In Logic File
private void collideBallObstacles(Ball ball,Obstacle rect){
if(rect.intersects(ball, rect)){
ball.velX *= -1;
ball.velY *= -1;
if (ball == player){
flashGreen();
obstaclesevaded--;
}
obstacles.remove(rect);
}
}
您还必须渲染它,并更改变量或创建适合此代码的变量。
只是好奇——这个游戏的名字会是什么?
推荐阅读
- sql-server - 如果我加入同一个表两次,则从表中获取属性失败
- c++ - 拥有适用于 Windows 10 的 CryptoProvider
- javascript - 使用字符串输入创建正则表达式对象
- firebase - 恢复已删除的 Firebase 集合
- javascript - Redux-Form 从另一个文件加载组件冻结加载
- javascript - 从重复对象数组中返回最新值
- html - 无序列表中的项目符号点位置不适用于文本区域
- c# - 过程或函数需要参数,该参数未提供但已提供参数
- sql - 从每日表构建每月聚合
- python - 在 python 中从 AWS 检索快照时间戳和 ID 的最简单方法?