冲突范围
GameObject.java
public abstract class GameObject{ private Transform _transform; private double _z; private Shape _collideBox; private int _colliderX = 0; private int _colliderY = 0; private int _colliderXscale = 0; private int _colliderYscale = 0; public GameObject(Transform trans, int hurtx, int hurty, int hurtscale_x, int hurtscale_y){ _transform = trans; this.setCollider(hurtx, hurty, hurtscale_x, hurtscale_y); } public Transform getTransform(){ return _transform; } public void move(double x,double y){ _z += y; _transform.translate(x,y); } public Shape getHurtBox(){ AffineTransform as = new AffineTransform(); as.setTransform(_transform.getTransform()); _collideBox = as.createTransformedShape(new Rectangle(_colliderX,_colliderY,_colliderXscale, _colliderYscale)); return _collideBox; } public void setCollider(int x1,int y1, int x2, int y2){ _colliderX = x1; _colliderY = y1; _colliderXscale = x2; _colliderYscale = y2; } public abstract void update(Graphics2D g); public double getZ(){ return _z; } public void setZ(double z){ _z = z; } public double getX(){ return _transform.getX(); } public double getY(){ return _transform.getY(); } }
getHurtBox的createTransformedShape是一个重要的方法,有必要解释一下:作用是基于sprite当前位置获取传入参数指定的矩形。
很多实体都有一个HurtBox(伤害盒子,用于人身攻击,冲突检测),故我们定义个基类GameObject,里面有2个主要的方法:
setCollider用来设置盒子范围;
getHurtBox返回当前对象的伤害盒子
让Player继承GameObject
public class Player extends GameObject{ public Player(Animator animator, int hurtx, int hurty, int hurtscale_x, int hurtscale_y){ super(animator,hurtx,hurty,hurtscale_x,hurtscale_y); _animator = animator; _animator.setAnimation("idle"); }
并在初始化时设置范围:
GameApp.java
Animator animator = new Animator(Config.PLAYER_JASMIN); _player = new Player(animator,60,44,18,98);
GameApp.java
我们可以通过调用以下方法,可视化player的被攻击范围
_gameLoop()
g.setColor(Color.red); g.draw(_player.getHurtBox());
如果您迷路了,请参考完整源码: