我正在为学校项目制作一款安卓游戏。我熟悉java,但没有制作游戏的经验。在我的游戏中,球由玩家控制。这个球需要反弹墙壁。
我试过两种方式,但都不成功。首先尝试:我能够检测到重叠,但无法检测球击中的一侧。
c =球,r =墙
float closestX = c.center.x;
float closestY = c.center.y;
if(c.center.x < r.topLeft.x) {
closestX = r.topLeft.x;
}
else if(c.center.x > r.topLeft.x + r.width) {
closestX = r.topLeft.x + r.width;
}
if(c.center.y < r.topLeft.y) {
closestY = r.topLeft.y;
}
else if(c.center.y > r.topLeft.y + r.height) {
closestY = r.topLeft.y + r.height;
}
return c.center.distSquared(closestX, closestY) < c.radius * c.radius;
所以我尝试了一种新的方法。但是这种方法很不稳定,并将球视为正方形。
cNew =下一个位置的球,cOld =当前位置的球,r =墙
if (cNew.center.x + cNew.radius >= r.topLeft.x && cNew.center.x - cNew.radius <= r.topLeft.x + r.width)
{
if (cOld.center.y + cOld.radius < r.topLeft.y && cNew.center.y + cNew.radius >= r.topLeft.y)
{
return Side.TOP;
}
else if (cOld.center.y - cOld.radius > r.topLeft.y + r.height && cNew.center.y - cNew.radius <= r.topLeft.y + r.height)
{
return Side.BOTTOM;
}
}
if (cNew.center.y + cNew.radius >= r.topLeft.y && cNew.center.y - cNew.radius <= r.topLeft.y + r.height)
{
if (cOld.center.x + cOld.radius < r.topLeft.x && cNew.center.x + cNew.radius >= r.topLeft.x)
{
return Side.LEFT;
}
else if (cOld.center.x - cOld.radius > r.topLeft.x + r.width && cNew.center.x - cNew.radius <= r.topLeft.x + r.width)
{
return Side.RIGHT;
}
}
return null;
我需要将这两者结合起来,但我还是找不到如何。
非常感谢帮助。
答案 0 :(得分:0)
没有仔细检查代码(考虑到这是你的学校项目,可能我不应该做你的功课),但我认为将球视为正方形不会有任何负面影响,如果是只是要从墙上反弹。还有其他你想做的事吗?
你的第一个代码遗漏了球的表面在其中心之前与墙碰撞的事实。您可能想要考虑到这一点。你的第二个代码在什么意义上不稳定?
更多细节在这里很有用。
答案 1 :(得分:0)
我将在这里告诉你我是怎么做到的: 对于你需要的玩家(以及每个敌人):
和:
和以下点数组(列表):
大纲:
- 你的球中的所有点,每个没有alpha = 0的像素,用于检查与墙壁的碰撞
Walls:
现在,执行以下操作:
你需要以下逻辑:
int miny=Integer.MAX_VALUE;
for (Point p:walls) { //For every point in the walls
if (p.x >= (int)x && p.x <= (int)x+w && (int)p.x-(int)x < lower_side.length) {
try {
Point p2=lower_side[(int)p.x-(int)x]; //Get the point that is on the same height as the walls point
if (p.y >= (int)(y+p2.y) && (int)(y+p2.y+yvel) >= p.y && p.y-p2.y-1 < miny) { //Check if you are going to hit the wall, and if it is earlier as the earliest point determined.
miny=p.y-p2.y-1d; //Where is the earliest point where this can happen
}
} catch (Exception bug) {
System.out.println(bug);
}
}
}
将此应用于所有方向和尺寸。
if (miny != Integer.MAX_VALUE) {
y=miny; //Set position over the wall
yvel=-(yvel*0.75); //Bounce off
}
如果您有任何疑问,请随时发表评论。