Android学习之控制飞机移动

效果图:
Android学习之控制飞机移动
文章图片

PlaneView.java

import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Canvas; import android.graphics.Paint; import android.view.View; public class PlaneView extends View{ public float currentX,currentY; Bitmap plane; //创建画笔 Paint p = new Paint(); public PlaneView(Context context) { super(context); plane = BitmapFactory.decodeResource(context.getResources(), R.drawable.plane); setFocusable(true); }@Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); canvas.drawBitmap(plane, currentX, currentY, p); } }

PlaneGame.java
import android.app.Activity; import android.os.Bundle; import android.util.DisplayMetrics; import android.view.Display; import android.view.KeyEvent; import android.view.View; import android.view.View.OnKeyListener; import android.view.WindowManager; public class MainActivity extends Activity{ //定义飞机的移动速度 private int speed = 10; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //全屏显示,不显示系统的状态栏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); /* *创建PlaneView组件 *这里可以传入this因为context是activity的父类 */ final PlaneView planeView = new PlaneView(this); setContentView(planeView); //获取窗口管理器 WindowManager windowManager = getWindowManager(); Display display = windowManager.getDefaultDisplay(); DisplayMetrics displayMetrics = new DisplayMetrics(); //获取屏幕宽和高 display.getMetrics(displayMetrics); //设置飞机的初始位置 planeView.currentX = displayMetrics.widthPixels / 2; planeView.currentY = displayMetrics.heightPixels - 40; //为draw组件键盘事件绑定监听器 planeView.setOnKeyListener(new OnKeyListener() {@Override public boolean onKey(View v, int keyCode, KeyEvent event) { //获取由哪个键触发的事件 switch (event.getKeyCode()) { //控制飞机下上左右移 case KeyEvent.KEYCODE_S: planeView.currentY += speed; break; case KeyEvent.KEYCODE_W: planeView.currentY -= speed; break; case KeyEvent.KEYCODE_A: planeView.currentX -= speed; break; case KeyEvent.KEYCODE_D: planeView.currentX += speed; break; default: break; } //通知planeView组件重绘 planeView.invalidate(); return true; } }); } }

【Android学习之控制飞机移动】这里飞机的上下左右移动方向的加减参照:
Android学习之控制飞机移动
文章图片

飞机图标:Android学习之控制飞机移动
文章图片

    推荐阅读