[AndEngine] Scrollable Background

在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);


你可能感兴趣的:(background)