在AndEngine中只有一個AutoParallaxBackground的例子可看,但是這個例子中背景是一直在不停移動的,如果你想要手動控制背景移動的話,下面的例子可以幫你~
首先要創建一個ScrollableParallaxBackground的類,繼承自ParallaxBackground
public class ScrollableParallaxBackground extends ParallaxBackground {
private float cameraPreviousX;
private float cameraOffsetX;
private Camera camera;
public ScrollableParallaxBackground(float pRed, float pGreen, float pBlue, Camera camera) {
super(pRed, pGreen, pBlue);
// TODO Auto-generated constructor stub
this.camera = camera;
cameraPreviousX = camera.getCenterX();
}
public void updateScrollEvents() {
if (cameraPreviousX != this.camera.getCenterX()) {
cameraOffsetX = cameraPreviousX - this.camera.getCenterX();
cameraPreviousX = this.camera.getCenterX();
}
}
public void scroll(int OffsetValue)
{
cameraOffsetX=OffsetValue;
}
@Override
public void onUpdate(float pSecondsElapsed) {
super.onUpdate(pSecondsElapsed);
this.mParallaxValue += (cameraOffsetX * 2) * pSecondsElapsed;
cameraOffsetX = 0;
}
}
然後需要你在遊戲的主場景中重寫以下方法
@Override
public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) {
if (pSceneTouchEvent.getAction() == MotionEvent.ACTION_DOWN) {
mTouchX = pSceneTouchEvent.getMotionEvent().getX();
} else if (pSceneTouchEvent.getAction() == MotionEvent.ACTION_MOVE) {
float newX = pSceneTouchEvent.getMotionEvent().getX();
mTouchOffsetX = (newX - mTouchX);
autoParallaxBackground.updateScrollEvents();
float newScrollX = mZoomCamera.getCenterX() - mTouchOffsetX;
mZoomCamera.setCenter(newScrollX, mZoomCamera.getCenterY());
mTouchX = newX;
}
return true;
}
以下是創建背景對象的實例
autoParallaxBackground=new ScrollableParallaxBackground(0, 0, 0,Camera);
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(25, backSprite));
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(10, middleSprite));
autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(15, frontSprite));
Scene.setBackground(autoParallaxBackground);