所以我被告知要在android中使用canvas创建一个简单的游戏,仅用于学校项目(这意味着我不能使用Android附带的任何扩展或游戏引擎),我想创建一个与玩家走动的简单2D游戏。
我这样做了:
public GameView(Context c) {
// TODO Auto-generated constructor stub
super(c);
this.c=c;
this.Sprite=BitmapFactory.decodeResource(getResources(), R.drawable.walk1);
this.Sprite=Bitmap.createScaledBitmap(Sprite, Sprite.getWidth()*2, Sprite.getHeight()*2, false);
sprite2=new Sprite("Spicy",Sprite);
this.requestFocus();
this.setFocusableInTouchMode(true);
animate1();
}
我创建了一个视图类,加载了一个简单的玩家精灵,创建了精灵类和一个处理程序 -
public void animate1(){
handlerAnimation100 = new Handler();
final Runnable r = new Runnable() {
public void run() {
invalidate();
handlerAnimation100.postDelayed(this, 1);
}
};
handlerAnimation100.postDelayed(r, 1);
}
对于游戏时间和动画,每0.001秒无效。
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
sprite2.Draw(canvas);
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
sprite2.Update(keyCode);
invalidate();
return false;
}
on onDraw我在sprite类和onkeydown中调用了draw函数,我将按键发送到精灵类中的更新函数。
现在对于精灵课来说,没有什么特别之处:
public class Sprite {
enum State
{
Walking
}
State mCurrentState = State.Walking;
int mDirection = 0;
int mSpeed = 0;
int mPreviousKeyboardState;
private String spriteName;
Bitmap sprite;
int SPRITE_SPEED = 5;
int MOVE_LEFT = -1;
int MOVE_RIGHT = 1;
private float mScale = 1.0f;
Point Position;
public Sprite(String name,Bitmap sprite) {
this.sprite=sprite;
this.spriteName=name;
Position=new Point(150,150);
}
public void Update(int keyboard)
{
int aCurrentKeyboardState = keyboard;
UpdateMovement(aCurrentKeyboardState);
mPreviousKeyboardState = aCurrentKeyboardState;
}
private void UpdateMovement(int aCurrentKeyboardState)
{
if (mCurrentState == State.Walking)
{
mSpeed = 0;
mDirection = 0;
if (aCurrentKeyboardState==KeyEvent.KEYCODE_A)
{
mSpeed = SPRITE_SPEED;
mDirection = MOVE_LEFT;
}
else if(aCurrentKeyboardState==KeyEvent.KEYCODE_D)
{
mSpeed = SPRITE_SPEED;
mDirection= MOVE_RIGHT;
}
Position.x += mDirection * mSpeed;
}
}
public void Draw(Canvas c)
{
c.drawBitmap(sprite, Position.x,Position.y, null);
}
}
我只是改变图像的位置并根据按下的键移动它。
现在出现问题: 使用handler和invalidate是我能够找到的唯一选项来替换"游戏时间"它出现在游戏引擎中,虽然它可以工作,但它的工作非常不稳定,如果播放器的速度很高,它看起来像是跳过像素,如果它低,动画模糊且非常慢,看起来无效需要更多的时间并且它不是每0.001秒而是0.5秒左右发生。
以下是它的样子:
慢速(模糊和非常慢):
速度更快(波动不顺畅):
有没有更好的方法,只使用Android提供的功能?
答案 0 :(得分:1)
线程!然而,处理程序不是问题的根源,判断动画的运行速度有多慢以及快速动作的波动程度如何,您可能正在使用绑定到ImageView的画布?这根本不是很快。您应该考虑使用SurfaceView(使用较低的API但不是最快的)或者使用TextureView(超快速,我不得不延迟我的线程因为动画只是模糊)。这两者都依赖于画布的核心。
互联网上有很多关于如何对这些进行编码的例子,你可以根据自己的需要调整它们。为了给你一个开始的地方,你可以看看HERE我写的一些样本。