您的位置:首页 > 移动开发 > Android开发

Android游戏开发中对象移动的例子

2009-08-27 23:07 549 查看
转载 : http://cwq.yfjhh.com/2009/05/android.html

该游戏对象移动,以view的背景作动画,假设开始的位置是父View坐标的(0,0)
游戏角色view的事件监听应该在父view中监听。
同时注意,AnimationDrawable.start()不能在Activity.onCreate事件未执行完就调用,
但可以用在比如点击按纽后就调用等。

public class Dog extends View implements OnKeyListener, Runnable {

// 左右移动对应不同的背景动画,用这个记下当前的背景动画
private AnimationDrawable nowAnim;
// 左移动对应的背景动画
private AnimationDrawable animLeft;
// 右移动对应的背景动画
private AnimationDrawable animRight;
private View parent;

// 记下view的坐标位置,用于移动后重画该区域。该坐标是相对于父View的。
// 同时要注意,如果父View是有padding的,要算上,因为是以父Vew的左上角点为原点的
// padding最好为每次位移量的正倍数。l,t,r,b为实时的坐标位置,step为每次位移量
private int l=0,t=0,r=22,b=20,step=3;

public Dog(Context context, View parent) {
super(context);
// TODO Auto-generated constructor stub
this.parent = parent;
// 记下父容器,即父View

l += parent.getPaddingLeft(); t += parent.getPaddingTop();
r += parent.getPaddingRight(); b += parent.getPaddingBottom();
// 如果父view有padding,要算上,因为view的坐标是以父view的左上角为原点的

// 生成左和右移动对应的背景动画,其实只是一个png,有对象移动时是的几个图片,将其分拆成移动的动画
animLeft = AndroidUtils.animationFromSplitImage(
context, R.drawable.woniu, 22, 20, 200);
// 只需一个移动方向的png就行了,该animationFromSplitImage函数是将图像水来翻转。
animRight = AndroidUtils.animationFromSplitImage(
AndroidUtils.imageFlipHorizintal(context, R.drawable.woniu), 22, 20, 200);

setAnimationDrawable( animRight );
//this.setOnKeyListener( this );

}

private void setAnimationDrawable(AnimationDrawable anim) {
if( nowAnim != null ) {
nowAnim.stop();
// 必须要先stop才行,不然会影响到下一个动画的情况
nowAnim = null;
}
nowAnim = anim;
this.setBackgroundDrawable(nowAnim);
}

// 返回当前的动画,用于在其它地方控制停止等。
public AnimationDrawable getBgAnimationDrawable() {
return nowAnim;
}

public boolean onKey(View v, int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if( event.getAction() == KeyEvent.ACTION_DOWN )
{
switch (keyCode)
{
case KeyEvent.KEYCODE_DPAD_LEFT: {
if( getLeft()>parent.getPaddingLeft() ) {
// 左或右位移量,是相对当前View的坐标
offsetLeftAndRight(-1*step);
// 记下当前的坐标值,用于在父view中重画经过的区域。
l -= step;
}
if( animLeft != nowAnim ) {
setAnimationDrawable( animLeft );
nowAnim.start();
}
break ;
}
case KeyEvent.KEYCODE_DPAD_RIGHT: {
if( getRight()<(parent.getWidth() - parent.getPaddingRight()) ) {
offsetLeftAndRight(step);
r += step;
}
if( animRight != nowAnim ) {
setAnimationDrawable( animRight );
nowAnim.start();
}
break ;
}
case KeyEvent.KEYCODE_DPAD_UP: {
if( getTop()>parent.getPaddingTop() ) {
offsetTopAndBottom(-1*step);
t -= step;
}
break ;
}
case KeyEvent.KEYCODE_DPAD_DOWN: {
if( getBottom()<(parent.getHeight() - parent.getPaddingBottom()) ) {
offsetTopAndBottom(step);
b += step;
}
break ;
}
case KeyEvent.KEYCODE_DPAD_CENTER: {
break ;
}
default: {}
}
repaint();
}
return true;
}

public void run() {
// TODO Auto-generated method stub
// 每次位移后,都重画位移前的区域的内容
parent.invalidate(l,t,r,b);
}

public void repaint() {
this.post(this);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐