Android game an collision
I have a many sprites walking on the screen. If the sprite s1 collides with sprite2, both sprites should play a sound (or similar).
I have created a game loop:
public void run( )
{
long startTime;
long sleepTime;
while (this.running)
{
startTime = System.currentTimeMillis();
this.view.updatePhysics( );
Canvas canvas = null;
try
{
canvas = this.view.getHolder( ).lockCanvas( );
synchronized (this.view.getHolder( ))
{
this.view.onDraw( canvas );
}
}
finally
{
if (canvas != null)
this.view.getHolder( ).unlockCanvasAndPost( canvas );
}
sleepTime = TICS_PRO_SECOND - ( System.currentTimeMillis( ) - startTime );
try
{
if (sleepTime > 0)
GameLoop.sleep( sleepTime );
else
GameLoop.sleep( 500 );
}
catch (Exception exception)
{
}
}
}
The updatePhysics() is called many times. If I use a debugger I can see, that the code execution in collideWith( Sprite sprite ) comes up to return true, but jump to the next line an return false. I think, it is a synchr开发者_JAVA百科onisation problem...
Where I should call the collision method in my game loop? Is the update() the right place? I think, it isn't ;) . The sprite.onCollision( ) is called very rare...
protected void updatePhysics( )
{
for (Sprite sprite : sprites)
{
for (Sprite s : sprites)
{
if (sprite.collideWith( s ))
sprite.onCollision( );
}
sprite.update( );
}
}
public boolean collideWith( Sprite sprite )
{
if (this == sprite)
return false;
Rect thisSprite = new Rect( this.xCoordinate, this.yCoordinate, this.width, this.height );
Rect anotherSprite = new Rect( sprite.xCoordinate, sprite.yCoordinate, sprite.width, sprite.height );
if (thisSprite.intersect( anotherSprite ))
return true;
return false;
}
Should I synchronized the collideWith() method? Or is my code
for (Sprite sprite : sprites)
{
for (Sprite s : sprites)
{
if (sprite.collideWith( s ))
sprite.onCollision( );
}
sprite.update( );
}
the problem?
Regards, Dulcinea
精彩评论