1. 位置:Modifier_example --> MovingBall
2. 類名:MovingBall
(1).精靈的移動我們可以在每次刷新的時候更新精靈的X, Y位置來達到移動的效果,下面我們用PhysicsHandler 事件來移動一個笑臉精靈,通過更改PhysicsHandler 事件的X, Y速率使精靈動起來。
/**
* 定義一個Ball精靈
* @author lin
*
*/
private static class Ball extends AnimatedSprite {
/**移動處理事件*/
private final PhysicsHandler mPhysicsHandler;//一個自動更新實體位置的IUpdateHandler邏輯事務
public Ball(final float pX, final float pY, String pTextureRegion, final VertexBufferObjectManager pVertexBufferObjectManager) {
super(pX, pY, pTextureRegion, pVertexBufferObjectManager);
this.mPhysicsHandler = new PhysicsHandler(this);//實例化事件
this.registerUpdateHandler(this.mPhysicsHandler);//註冊事件,註冊後纔會被執行
this.mPhysicsHandler.setVelocity(DEMO_VELOCITY, DEMO_VELOCITY);//設置X, Y速率
}
//控制精靈永遠在屏幕內移動,不會超出屏幕外
@Override
protected void onManagedUpdate(final float pSecondsElapsed) {
if(this.mX < 0) {//ball 精靈x座標小於0時
this.mPhysicsHandler.setVelocityX(DEMO_VELOCITY);//設置x速率爲正,即往右移動
} else if(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速率爲正,即往下移動
} else if(this.mY + this.getHeight() >= SCENE_HEIGHT) {//ball 精靈y座標大於屏幕下邊時
this.mPhysicsHandler.setVelocityY(-DEMO_VELOCITY);//設置y速率爲負,即往上移動
}
super.onManagedUpdate(pSecondsElapsed);//執行父類的方法
}
}