主要类是:
public class test extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new Game(this,null));
}
}
Game类从视图类扩展到允许我们绘制汽车并设置其位置,我调用onkey方法来控制汽车的方向和角度
public class Game extends View {
private Paint paint= new Paint();
float x,y;
float speed = 5,angle = 0,mod = 0;
Bitmap car;
Boolean b=false;
public Game(Context context, AttributeSet attrs) {
super(context, attrs);
try { // here I call the car image as a bitmap object
AssetManager assetManager=context.getAssets();
InputStream inputStream= assetManager.open("car.png");
BitmapFactory.Options options=new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_4444;
car=BitmapFactory.decodeStream(inputStream,null,options);
inputStream.close();
Log.d("Bitmap Text", "bobrgb888.png format: "+car.getConfig());
} catch (Exception e) {
// TODO: handle exception
}
}
@Override
protected void onDraw(Canvas canvas) {
x += (speed*mod) * Math.cos(Math.PI/180 * angle);
y += (speed*mod) * Math.sin(Math.PI/180 * angle);
canvas.rotate((float) (Math.PI/180 * angle));
canvas.drawBitmap(car,-(car.getWidth()/2), -(car.getHeight()/2), null);
canvas.restore();
}
public boolean onKey(View view, int keyCode, KeyEvent event) {
switch (event.getAction()) {
case KeyEvent.ACTION_DOWN:
break;
case KeyEvent.ACTION_UP:
{if(event.getKeyCode() == KeyEvent.KEYCODE_A || event.getKeyCode() == KeyEvent.KEYCODE_B)
{
this.mod = 0;
}}
break;
case KeyEvent.ACTION_MULTIPLE:{
if(event.getKeyCode() == KeyEvent.KEYCODE_A)
{
mod = 1;
}
if(event.getKeyCode() == KeyEvent.KEYCODE_B)
{
mod = -1;
}
if(event.getKeyCode() == KeyEvent.KEYCODE_C)
{
angle -= 5;
}
if(event.getKeyCode() == KeyEvent.KEYCODE_D)
{
angle+=5;
}
}
break;
}
invalidate();
return event.getKeyCode() != KeyEvent.KEYCODE_BACK;
}
}
我设置了下一个点的x和y 我按照选定的角度旋转图像 我把汽车拉到当前位置。 当钥匙A或B上升时,汽车停止 当按键长时间(A,B,C,D)时,角度和方向会发生变化。
答案 0 :(得分:1)
使用它:
@Override
public boolean onKeyDown(View view, Editable arg1, int keyCode, KeyEvent event) {
而不是:
public boolean onKey(View view, int keyCode, KeyEvent event) {