问题描述
我在写作的游戏中显示了两个角色,玩家和敌人。定义如下:
I have two characters displayed in a game I am writing, the player and the enemy. defined as such:
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);
我可以用键盘移动玩家(),但我在尝试时不知所措检测两者之间的碰撞。很多人都说使用矩形,但作为一个初学者,我看不出如何将它链接到我现有的代码中。任何人都可以为我提供一些建议吗?
I am able to move player() around with the keyboard, but I am at a loss when trying to detect a collision between the two. A lot of people have said to use Rectangles, but being a beginner I cannot see how I would link this into my existing code. Can anyone offer some advice for me?
推荐答案
我认为你的问题是你没有为你的播放器使用优秀的OO设计敌人。创建两个类:
I think your problem is that you are not using good OO design for your player and enemies. Create two classes:
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,Width和Height变量。
Your Player should have X,Y,Width,and Height variables.
你的敌人也应该。
在你的游戏中循环,做这样的事情(C#):
In your game loop, do something like this (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();
}
}
为了加快速度,请不要费心检查是否敌人的坐标在屏幕外。
To speed things up, don't bother checking if the enemies coords are offscreen.
这篇关于Java中两个图像之间的碰撞检测的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!