Reputation: 770
I'm a beginner at Android Development.
I've created a game. One Bitmap (1) is controllable, the other bitmap (2) acts on collision with the first. Works fine. Question ; How would I create multiple instances of (2) that would, to start with, all respond to a collision with (1) in the same way.
What I've built so far;
In the MainGamePanel, I create the two Bitmaps :
basket = new basket(BitmapFactory.decodeResource(getResources(), R.drawable.basket01), 50, 50);
apple = new apple(BitmapFactory.decodeResource(getResources(), R.drawable.apple_red01));
The MainThread performs update and draws the canvas on the panel
In the update (in MainGamePanel), I check for collisions between (1) and (2), checking the coordinates.
If collision detected, I set coordinates on apple (2), it becomes 'slotted'.
Then, if apple (2) is slotted AND touched, I move it to a random position on the screen and set the boolean slotted to false.
... this is where I'm stuck, 2 questions (should I split them up here on SO?)
Thanks!
Current Code-snippets for the bitmap (2) "apple" :
public void draw(Canvas canvas) {
canvas.drawBitmap(bitmap, X - width/2, Y - height/2, null);
}
With regards to question two (review random generator, I need to set max values);
if (slotted){
if (eventX >= (X - width/ 2) && (eventX <= (X + width/2))) {
if (eventY >= (Y - height/ 2) && (eventY <= (Y + height/ 2))) {
// basket touch
Random Rnd = new Random();
float nX=Rnd.nextInt(HOWTOMAXOFVIEWORCANVAS);
float nY=Rnd.nextInt(HOWTOMAXOFVIEWORCANVAS)+80;
// the +80 is to prevent the apple from returning in the 'slotted' area (the basket can't get there ;)
setX(nX);
setY(nY);
slotted = false;
Upvotes: 0
Views: 923
Reputation: 20309
A very simple way would be to create a list
of apples instead of separate apple instances:
ArrayList<apple> appleList = new ArrayList<apple>();
int nApples = 5;
for (int i=0; i<5; i++)
appleList.add(new apple();
You DO NOT WANT want to create multiple instances of a bitmap. Bitmaps can consume a large amount of memory 4 bytes per pixel. Its would be many times better to simply create the bitmap once and then just have your apple objects reference that bitmap directly.
The max X and Y values of the canvas are determined by the dimensions of the View
you are drawing to. Once your View
has been inflated and drawn you should be able to get those values from the view.
Upvotes: 1