1.位置:Modifier_example-->MovingBall2.类名:MovingBall

(1).精灵的移动我们可以在每次刷新的时候更新精灵的X,Y位置来达到移动的效果,下面我们用PhysicsHandler事件来移动一个笑脸精灵,通过更改PhysicsHandler事件的X,Y速率使精灵动起来。

/**
*定义一个Ball精灵
*@authorlin
*
*/
privatestaticclassBallextendsAnimatedSprite{
/**移动处理事件*/
privatefinalPhysicsHandlermPhysicsHandler;//一个自动更新实体位置的IUpdateHandler逻辑事务

publicBall(finalfloatpX,finalfloatpY,StringpTextureRegion,finalVertexBufferObjectManagerpVertexBufferObjectManager){
super(pX,pY,pTextureRegion,pVertexBufferObjectManager);
this.mPhysicsHandler=newPhysicsHandler(this);//实例化事件
this.registerUpdateHandler(this.mPhysicsHandler);//注册事件,注册后才会被执行
this.mPhysicsHandler.setVelocity(DEMO_VELOCITY,DEMO_VELOCITY);//设置X,Y速率
}

//控制精灵永远在屏幕内移动,不会超出屏幕外
@Override
protectedvoidonManagedUpdate(finalfloatpSecondsElapsed){
if(this.mX<0){//ball精灵x坐标小于0时
this.mPhysicsHandler.setVelocityX(DEMO_VELOCITY);//设置x速率为正,即往右移动
}elseif(this.mX+this.getWidth()>=SCENE_WIDTH){//ball精灵x坐标大于屏幕右边时,即快移出屏幕右边
this.mPhysicsHandler.setVelocityX(-DEMO_VELOCITY);//设置x速率为负,即往左移动
}

if(this.mY<0){//ball精灵y坐标小于0时
this.mPhysicsHandler.setVelocityY(DEMO_VELOCITY);//设置y速率为正,即往下移动
}elseif(this.mY+this.getHeight()>=SCENE_HEIGHT){//ball精灵y坐标大于屏幕下边时
this.mPhysicsHandler.setVelocityY(-DEMO_VELOCITY);//设置y速率为负,即往上移动
}

super.onManagedUpdate(pSecondsElapsed);//执行父类的方法
}
}

OGE_Example项目源码