主要知识点:
1 setBounds 限制镜头跟随的范围
camera
..viewfinder.visibleGameSize = Vector2(size.x, size.y)
..follow(player);
//代表Camera 跟随移动的范围 超过这个范围 就不跟随了
camera.setBounds(Rectangle.fromCenter(center: Vector2.zero(), size: Vector2(size.x, 0)));
world.add(player);
2 监听按键修改人物移动方向
void onKeyEvent(KeyEvent event, Set<LogicalKeyboardKey> keysPressed){
//判断键盘按下 上 下 左 右 方向
final isKeyDown = event is KeyDownEvent;
final keyLeft = (event.logicalKey == LogicalKeyboardKey.arrowLeft) ||
(event.logicalKey == LogicalKeyboardKey.keyA);
final keyRight = (event.logicalKey == LogicalKeyboardKey.arrowRight) ||
(event.logicalKey == LogicalKeyboardKey.keyD);
final keyUp = (event.logicalKey == LogicalKeyboardKey.arrowUp) ||
(event.logicalKey == LogicalKeyboardKey.keyW);
debugPrint("=====KeyDownEvent===${event}");
debugPrint("=====KeyDownEvent===${keysPressed.contains(LogicalKeyboardKey.keyA)}");
if (isKeyDown) {
if (keyLeft) {
velocity.x = -runSpeed;
} else if (keyRight) {
velocity.x = runSpeed;
}else if(keyUp){
velocity.y = -runSpeed;
}else {
velocity.y = runSpeed;
}
} else {
final hasLeft = keysPressed.contains(LogicalKeyboardKey.arrowLeft) ||
keysPressed.contains(LogicalKeyboardKey.keyA);
final hasRight = keysPressed.contains(LogicalKeyboardKey.arrowRight) ||
keysPressed.contains(LogicalKeyboardKey.keyD);
final hasTop = keysPressed.contains(LogicalKeyboardKey.arrowUp) ||
keysPressed.contains(LogicalKeyboardKey.keyW);
final hasBottom = keysPressed.contains(LogicalKeyboardKey.arrowDown) ||
keysPressed.contains(LogicalKeyboardKey.keyS);
if (hasLeft && hasRight) {
// Leave the current speed unchanged
} else if (hasLeft) {
velocity.x = -runSpeed;
} else if (hasRight) {
velocity.x = runSpeed;
} else {
velocity.x = 0;
}
if (hasTop && hasBottom) {
// Leave the current speed unchanged
} else if (hasTop) {
velocity.y = -runSpeed;
} else if (hasBottom) {
velocity.y = runSpeed;
} else {
velocity.y = 0;
}
}
if(velocity.y > 0){
animation = bottomAnim;
}else if(velocity.y < 0){
animation = topAnim;
}else if(velocity.x > 0){
animation = rightAnim;
}else if(velocity.x < 0){
animation = leftAnim;
}else {
animation = bottomAnim;
}
}
3 update 方法中更新人物位置
@override
void update(double dt) {
super.update(dt);
position.x += velocity.x * dt;
position.y += velocity.y * dt;
if(position.x < -game.gameTotalSize.x / 2){
position.x = -game.gameTotalSize.x / 2;
}else if(position.x > game.gameTotalSize.x / 2){
position.x = game.gameTotalSize.x / 2;
}
if(position.y < -game.gameTotalSize.y / 2){
position.y = -game.gameTotalSize.y / 2;
}else if(position.y > game.gameTotalSize.y / 2){
position.y = game.gameTotalSize.y / 2;
}
}