控制飞机的移动

/*
 * 控制飞机的移动
 * 游戏中的飞机会随用户单击键盘的动作而移动
 */
import 略
public class Ex003_01Activity extends Activity {
	// 飞机移动的速度
	private int speed = 12;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// setContentView(R.layout.main);
		// 去掉窗口标题
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		// 全屏显示
		getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
		// 创建planeView组件
		final planeView planeview = new planeView(this);
		this.setContentView(planeview);
		planeview.setBackgroundResource(R.drawable.back);
		// 获取窗口管理器
		WindowManager windowManager = getWindowManager();
		Display display = windowManager.getDefaultDisplay();
		// 获得屏幕的宽和高
		int screenWith = display.getWidth();
		int screenHeight = display.getHeight();
		// 设置飞机的初始位置
		planeview.currentX = screenWith / 2;
		planeview.currentY = screenHeight - 60;
		// 为draw组件的键盘事件绑定监听器
		planeview.setOnKeyListener(new OnKeyListener() {

			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				switch (event.getKeyCode()) {
				case KeyEvent.KEYCODE_DPAD_DOWN:
					planeview.currentY += speed;
					break;
				case KeyEvent.KEYCODE_DPAD_UP:
					planeview.currentY -= speed;
					break;
				case KeyEvent.KEYCODE_DPAD_RIGHT:
					planeview.currentX += speed;
					break;
				case KeyEvent.KEYCODE_DPAD_LEFT:
					planeview.currentX -= speed;
					break;
				default:
					break;
				}
				// 重绘组件
				planeview.invalidate();
				return true;
			}
		});

		/*******************************************/
		planeview.setOnTouchListener(new OnTouchListener() {

			@Override
			public boolean onTouch(View v, MotionEvent event) {
				// TODO Auto-generated method stub
				float X = event.getX();
				// float Y = event.getY();
				if (planeview.currentX < X) {
					planeview.currentX += speed;
				} else {
					planeview.currentX -= speed;
				}
				planeview.invalidate();
				return true;
			}
		});
		/****************************************** */
	}
}

// 自定义一个View,该View负责绘制游戏的飞机
class planeView extends View {
	public float currentX;
	public float currentY;
	Bitmap plane;

	public planeView(Context context) {
		super(context);
		// TODO Auto-generated constructor stub
		// 定义飞机图片
		plane = BitmapFactory.decodeResource(context.getResources(),
				R.drawable.plane);
		setFocusable(true);
	}

	public void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		// 创建画笔
		Paint p = new Paint();
		// 绘制飞机
		canvas.drawBitmap(plane, currentX, currentY, p);
	}
}
下面我们来看下运行结果:
控制飞机的移动_第1张图片

你可能感兴趣的:(控制飞机的移动)