内容来自RyiSnow视频讲解
拾取物品
这一节实现了简单的玩家拾取游戏物品,拾取钥匙,用于打开门,拾取靴子,增加移动速度,最终的目标是拾取3把钥匙,打开3扇门,获得宝箱。
值的一提的是,这一节的collision chek碰撞检测使用的是Rectangle类的intersects(Rectangle r)
方法,此方法简洁又方便,作者还特地提到了,为什么player移动与墙的collision check碰撞检测没有使用这个方法实现,从实际实现上说是可以用的,只是之前的实现方法每个方向只需要检测2个点,上述方法需要检测4个点,之前的方法相对来说更高效。
Rectangle类的检测矩形碰撞方法
public boolean intersects(Rectangle r) {
int tw = this.width;
int th = this.height;
int rw = r.width;
int rh = r.height;
if (rw <= 0 || rh <= 0 || tw <= 0 || th <= 0) {
return false;
}
int tx = this.x;
int ty = this.y;
int rx = r.x;
int ry = r.y;
rw += rx;
rh += ry;
tw += tx;
th += ty;
// overflow || intersect
return ((rw < rx || rw > tx) &&
(rh < ry || rh > ty) &&
(tw < tx || tw > rx) &&
(th < ty || th > ry));
}
当然也要看实际的游戏需求,灵活选择适当的方法,不能拘泥成例。
在拾取靴子增加移动速度的时候,要注意不能把速度增加的过多,不然容易出现移动速度过快,不好控制player,尤其通过狭窄通道的时候。