我正在制作一个游戏,我需要大约50个小虫子从各个方向进入场景。我想让他们在屏幕上随意移动,但这似乎不可能。似乎如果我使用MoveModifier,我必须为每个精灵提供一个结束位置。有没有什么方法可以做到这一点,而不使用移动修改器。我不熟悉box 2d扩展,但我看到很多人都用它来移动精灵,把它们连接到物理体上。我需要延期吗?我不清楚。此外,我需要精灵检测自己和其他动画精灵之间的碰撞检测。我不太清楚我该怎么做。请帮忙。以下是我的代码。。看起来对吗
private Runnable mStartMosq = new Runnable() {
public void run() {
getWindowManager().getDefaultDisplay().getMetrics(dm);
Log.d("Level1Activity", "width " + dm.widthPixels + " height " + dm.heightPixels);
int i = nMosq++;
Scene scene = Level1Activity.this.mEngine.getScene();
float startX = gen.nextFloat() * CAMERA_WIDTH;
float startY = gen.nextFloat() * (CAMERA_HEIGHT); // - 50.0f);
sprMosq[i] = new Sprite(startX, startY,
mMosquitoTextureRegion,getVertexBufferObjectManager());
body[i] = PhysicsFactory.createBoxBody(mPhysicsWorld, sprMosq[i], BodyType.DynamicBody, FIXTURE_DEF);
sprMosq[i].registerEntityModifier(new SequenceEntityModifier(
new AlphaModifier(5.0f, 0.0f, 1.0f),
new MoveModifier(60.0f, sprMosq[i].getX(), dm.widthPixels/2 , sprMosq[i].getY(), dm.heightPixels/2 , EaseBounceInOut.getInstance())));
scene.getLastChild().attachChild(sprMosq[i]);
mPhysicsWorld.registerPhysicsConnector(new PhysicsConnector(sprMosq[i], body[i], true, true));
if (nMosq < 50) {
mHandler.postDelayed(mStartMosq, 5000);
}
}
};
老实说,对于这个问题,你不需要box2d,除非你想在bug冲突时做一些花哨的事情。要做到这一点,您需要使用IUpdateHandler。我将给你一个粗略的例子,说明我将如何解决你的问题:
//Velocity modifier for the bugs. Play with this till you are happy with their speed
private final velocity = 1.0f;
sprMosq[i] = new Sprite(startX, startY,
mMosquitoTextureRegion,getVertexBufferObjectManager());
//Register update handlers
sprMosq[i].registerUpdateHandler(new IUpdateHandler(){
@Override
public void onUpdate(float pSecondsElapsed) {
//First check if this sprite collides with any other bug.
//you can do this by creating a loop which checks every sprite
//using sprite1.collidesWith(sprite2)
if(collision){
doCollisionAction(); //Whatever way you want to do it
} else {
float XVelocity; //Velocity on the X axis
float YVelocity; //Velocity on the Y axis
//Generate a different random number between -1 and 1
//for both XVelocity and YVelocity. Done using Math.random I believe
//Move the sprite
sprMosq[i].setPosition(XVelocity*velocity*pSecondsElapsed,
YVelocity*velocity*pSecondsElapsed);
}
}
@Override
public void reset() {
}
});
这将导致每个bug在游戏的每一帧渲染时随机移动。如果你想添加更多的bug并消耗处理能力,你可以降低随机性的频率,但你可能想像这种算法一样,少检查每一帧。要做到这一点,您可能需要使用TimerHandler,它会在一定的持续时间后自动重置。