我正在编写的游戏中显示了两个角色:玩家和敌人。定义如下:
public void player(Graphics g) {
g.drawImage(plimg, x, y, this);
}
public void enemy(Graphics g) {
g.drawImage(enemy, 200, 200, this);
}
然后调用:
player(g);
enemy(g);
我可以用键盘移动player(),但在尝试检测两者之间的碰撞时我不知所措。很多人都说要使用矩形,但作为初学者,我不知道如何将其链接到我现有的代码中。有人可以给我一些建议吗?
我认为你的问题是你没有为你的玩家和敌人使用良好的面向对象设计。创建两个类:
public class Player
{
int X;
int Y;
int Width;
int Height;
// Getters and Setters
}
public class Enemy
{
int X;
int Y;
int Width;
int Height;
// Getters and Setters
}
您的播放器应该有 X、Y、宽度和高度变量。
你的敌人也应该如此。
在你的游戏循环中,执行如下操作 (C#):
foreach (Enemy e in EnemyCollection)
{
Rectangle r = new Rectangle(e.X,e.Y,e.Width,e.Height);
Rectangle p = new Rectangle(player.X,player.Y,player.Width,player.Height);
// Assuming there is an intersect method, otherwise just handcompare the values
if (r.Intersects(p))
{
// A Collision!
// we know which enemy (e), so we can call e.DoCollision();
e.DoCollision();
}
}
为了加快速度,不必费心检查敌人坐标是否在屏幕外。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)