Working on game. I have a movable basket and a – for now – stationairy apple. In the Update step of the game, I check for collisions between the two. In the future, I want to add multiple apples, so I’m looking for the best way to detect collision between the basket and apple x.
Got code:
public void update() {
int basketcenterX = basket.getX() + (basket.getWidth() / 2);
int basketcenterY = basket.getY() + (basket.getHeight() / 2);
if (basketcenterX < apple.getX() + apple.getWidth() && basketcenterX > apple.getX())
if ( basketcenterY < apple.getY() + apple.getHeight() && basketcenterY > apple.getY())
{
Log.d(TAG, "Collision detected!!");
}
Log.d(TAG, "Apple Safe!");}
It seems pretty laggy in the emulator, I’m worried that it will be too slow when I add more apple-instances. Any suggestions on how to improve this and / or how to revamp this to check multiple apples?
There are 2 main improvements for your code.
Access methods
Don’t use getters and setters toO excessively. Those cannot be optimized in android in contrast to normal java applications. Just make public properties like
and access them directly.
Precalculate
You don’t want to move and have the bitmaps left top. You want to have its position and its position is its center. So wrap your bitmaps into a custom class
GameObjector similar and precalculate the center. You just modify the center.Store width and height of your bitmap in public fields of your
GameObjectclass and access them directly.}
If you are still concerned about performance, you also may precalculate the
width/2andheight/2.