java检测碰撞,Java中两个图像之间的碰撞检测

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);

}

Then called with:

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?

解决方案

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

}

Your Player should have X,Y,Width,and Height variables.

Your enemies should as well.

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值