设置player移动范围
config.java
我们的窗口size是640*480
public final static int BOUND_LEFT = 50; public final static int BOUND_RIGHT = 555; public final static int BOUND_TOP = 150; public final static int BOUND_BOTTOM = 330;
player.java
上下左右箭头控制player移动时,增加边界判断
private int _topLocked = 0; private int _bottomLocked = 0; private int _leftLocked = 0; private int _rightLocked = 0; private void _handleMovement(){ _keyPressed = false; if(_input.isKeyDown(KeyEvent.VK_UP) && getZ() > _topLocked){ _keyPressed = true; move(0, -_yspeed); } if(_input.isKeyDown(KeyEvent.VK_DOWN) && getZ() < _bottomLocked){ _keyPressed = true; move(0, _yspeed); } if(_input.isKeyDown(KeyEvent.VK_RIGHT) && _animator.getX() < _rightLocked) { _keyPressed = true; move(_xspeed,0); } if(_input.isKeyDown(KeyEvent.VK_LEFT) && _animator.getX() > _leftLocked) { _keyPressed = true; move(-_xspeed,0); } if(!_keyPressed){ _animator.setAnimation("idle"); _animator.translate(0,0); } }
GameApp.java
初始时设置四周边缘阈值
_player.setLockedBounds(Config.BOUND_TOP, Config.BOUND_BOTTOM, Config.BOUND_LEFT, Config.BOUND_RIGHT);
如果您迷路了,请查看本节完整源码: