我必须创建一个游戏,其中有一个玩家精灵和几个(大约 30 个)其他精灵在屏幕上随机移动而不会相互碰撞。我在避免碰撞方面遇到了问题,因为在检测到碰撞时,所有移动的精灵都被锁定了。下面是我的代码..在我的代码中,我创建了两个类,一个是MainActivity
(这是使用该类扩展BaseGameActivity
并创建大约 30 个AnimatedSprites
的主类,NewSprite
并包含 NewSprite 对象的静态数组列表“playerSprite”(大约 30 个随机创建的对象)第二个是NewSprite
(它扩展AnimatedSprite
并重载了该方法onManagedUpdate()
,以防止这些移动AnimatedSprites
离开屏幕并在它们之间发生碰撞。)
我只显示了NewSprite
类..
public class NewSprite extends AnimatedSprite{
public PhysicsHandler physicsHandler;
Random randPos;
public NewSprite(final float pX, final float pY, final ITiledTextureRegio pTiledTextureRegion, final VertexBufferObjectManager pVertexBufferObjectManager) {
super(pX, pY, pTiledTextureRegion, pVertexBufferObjectManager);
randPos = new Random();
float x1;
float y1;
while((x1 = randPos.nextFloat()) < 0.8f);
while((y1 = randPos.nextFloat()) < 0.8f);
if(randPos.nextInt() % 2 == 0)
x1 *= -1;
if(randPos.nextInt() % 2 == 0)
y1 *= -1;
physicsHandler = new PhysicsHandler(this);
this.registerUpdateHandler(physicsHandler);
physicsHandler.setVelocity(x1 * 100, y1 * 100);
}
@Override
protected void onManagedUpdate(float pSecondsElapsed) {
// TODO Auto-generated method stub
if(this.mX < 0){
this.move++;
float x2,y2;
while((x2 = randPos.nextFloat()) < 0.8f);
while((y2 = randPos.nextFloat()) < 0.8f);
if(randPos.nextInt() % 2 == 0)
y2 *= -1;
physicsHandler.setVelocity( x2*40, y2*40);
this.prevX = this.mX;
this.prevY = this.mY;
}
else if(this.mY < 0){
this.move++;
float x2,y2;
while((x2 = randPos.nextFloat()) < 0.8f);
while((y2 = randPos.nextFloat()) < 0.8f);
if(randPos.nextInt() % 2 == 0)
x2 *= -1;
physicsHandler.setVelocity( x2*40, y2*40);
this.prevX = this.mX;
this.prevY = this.mY;
}
else if(this.mX > (MainActivity.CAMERA_WIDTH - MainActivity.MONSTER_WIDTH)){
this.move++;
float x2,y2;
while((x2 = randPos.nextFloat()) < 0.8f);
while((y2 = randPos.nextFloat()) < 0.8f);
x2 *= -1;
if(randPos.nextInt() % 2 == 0)
y2 *= -1;
physicsHandler.setVelocity( x2*40, y2*40);
this.prevX = this.mX;
this.prevY = this.mY;
}
else if(this.mY > (MainActivity.CAMERA_HEIGHT - MainActivity.MONSTER_HEIGHT)){
this.move++;
float x2,y2;
while((x2 = randPos.nextFloat()) < 0.8f);
while((y2 = randPos.nextFloat()) < 0.8f);
if(randPos.nextInt() % 2 == 0)
x2 *= -1;
y2 *= -1;
physicsHandler.setVelocity( x2*40, y2*40);
this.prevX = this.mX;
this.prevY = this.mY;
}
for(int i=0 ; i < MainActivity.playerSprite.size(); i++){
if(( MainActivity.playerSprite.get(i)).collidesWith(this) || this.collidesWith(MainActivity.playerSprite.get(i))){
float x2, y2;
while((x2 = randPos.nextFloat()) < 0.8f);
while((y2 = randPos.nextFloat()) < 0.8f);
if(randPos.nextInt() % 2 == 0)
x2 *= -1;
if(randPos.nextInt() % 2 == 0)
y2 *= -1;
this.physicsHandler.setVelocity( x2*100, y2*100);
break;
}
}
super.onManagedUpdate(pSecondsElapsed);
}