我想为Android设备制作一个小游戏。 所有作品......除了与玩家和物体的碰撞。我做错什么了吗?我已经尝试了很多检查碰撞的方法。 E. g。相交,交叉,包含和自制碰撞试验的功能。
编辑:我的问题是没有任何反应:)
DisplayMetrics metrics = getContext().getResources().getDisplayMetrics();
int width = metrics.widthPixels;
int height = metrics.heightPixels;
private Bitmap player, enemy;
private int speedrun=1, x= 0, y = height - height / 5, i=1, yg=height - height / 5 + 40, xe= 920, xp =width / 2 - width / 4;
private Rect p, e;
public static int speed=0;
//other code
@Override
protected void onDraw(Canvas c)
{
c.drawColor(Color.CYAN);
handelPlayer();
p = new Rect(xp, y, 0, 0);
wayrect = new Rect(x, yg, 0, 0);
wayrect2 = new Rect(x + width, yg, 0, 0);
e = new Rect(xe, yg - 250, 0, 0);
c.drawBitmap(enemy, e.left, e.top, null);
c.drawBitmap(player, p.left, p.top, null);
}
public void handelPlayer()
{
x -= speed*speedrun;
xe -= speed*speedrun;
if (x + width < 0)
x = 0;
if (xe < -100)
xe = 920;
if (MainActivity.touch == 1)
{
y -= 100;//jump
MainActivity.touch = 0;
i = 1;
}
if (y <= height - height / 5)
y += 3 * i / 10; //gravity
i++;
if (p.intersect(e)) //collosision
speedrun = 0;
}
答案 0 :(得分:1)
首先,您的矩形从播放器位图的顶部移动到设备左上角的(0,0)。我想象的是你的意思:p = new Rect(xp, y, xp + player.getWidth(), y + player.getHeight());
和e
相同,请参阅下面的代码。
其次,p.intersect(e)
将矩形p更改为相交的交叉点,因此您应该使用Rect.intersects(p, e)
代替。
第三,您正在检查旧位置值的碰撞,因为您在更改位置后没有更新矩形。
快速修复可能是将交叉点测试移到handelPlayer
的顶部(次要注释:handlePlayer
将是拼写它的正确方法),如下所示:
protected void onDraw(Canvas c)
{
c.drawColor(Color.CYAN);
handelPlayer();
p = new Rect(xp, y, xp + player.getWidth(), y + player.getHeight());;
wayrect = new Rect(x, yg, 0, 0); // These rectangles also has their right bottom corner at (0,0), which might cause problems
wayrect2 = new Rect(x + width, yg, 0, 0);
e = new Rect(xe, yg - 250, xe + enemy.getWidth(), yg - 250 + enemy.getHeight()) ;
c.drawBitmap(enemy, e.left, e.top, null);
c.drawBitmap(player, p.left, p.top, null);
}
public void handelPlayer()
{
if (Rect.intersects(p, e)){ //collision
speedrun = 0;
}
x -= speed*speedrun;
xe -= speed*speedrun;
if (x + width < 0)
x = 0;
if (xe < -100)
xe = 920;
if (MainActivity.touch == 1)
{
y -= 100;//jump
MainActivity.touch = 0;
i = 1;
}
if (y <= height - height / 5)
y += 3 * i / 10; //gravity
i++;
}
可能还有另一个问题,因为你还没有描述到底发生了什么。