开发者同学都希望能做出优秀的游戏,在2D游戏中,使用parallax背景可以让单调的2D背景变得错落有致,让整个背景看起来更有立体的感觉,增强游戏体验和代入感
每次拖动界面,分层背景中的每一层都会随着屏幕一起移动,但是单位移动的速度确不同,这样就可以营造出一种远近背景错落有致的视觉效果
经典案例:还是愤怒的小鸟。。。。
好吧,在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);