Hello guys I hope you can help me. I try to code a game but I fail at collision. I searched a lot and found out that the bounding box method (to create a unvisible rectangle around the sprite) is the best soulution for me. But the intersect method is not working for me. I have two bitmap sprites which collide, but in the LogCat there is no collision…
Sprite No. 1 Class
public Sprite(GameView theGameView, Bitmap bmp) {
this.theGameView = theGameView;
this.bmp = bmp;
this.width = bmp.getWidth();
this.height = bmp.getHeight();
ySpeed = 0;
xSpeed = 1;
}
public Rect bounds() {
return (new Rect(x,y,width,height));
}
public void onDraw(Canvas canvas) {
canvas.drawBitmap(bmp, x, y, null);
}
Sprite No. 2 Class
public FourthSprite(GameView theGameView, Bitmap bmp) {
this.theGameView = theGameView;
this.bmp = bmp;
this.width = bmp.getWidth();
this.height = bmp.getHeight();
ySpeed = 0;
xSpeed = -1;
}
public Rect bounds() {
// TODO Auto-generated method stub
return (new Rect(x,y,width,height));
}
public void onDraw(Canvas canvas) {
canvas.drawBitmap(bmp, x, y, null);
}
}
GameView Class
public void collision() {
Rect r1 = theSprite.bounds(); // Sprite on left side
Rect r4 = theSprite4.bounds(); // Sprite on right side
if (r1.intersect(r4)){
collision = true;
Log.v("Log Tag", "COLLISION :D :D :D :D :D :D :D");
}
else {
collision = false;
Log.v("Log Tag", "NO COLLISION");
}
}
If it helps i can also upload a video.
Edit: http://youtu.be/wYxZ7nKsmdw
I figured out, that collision is working, when one sprite does not move arround and the x,y coordinates are 0. What could be the problem?
According to the video and the data you’re outputting into LogCat, something seems to be wrong with the move function (which hasn’t been listed in your question).
The
leftcoordinates of the rectangles are changing, however therightcoordinates aren’t. After some time theleftcoordinate of one rectangle becomes greater thanrightcoordinate, which results in theintersectsfunction to return false.On a side note, you should think about structuring your code differently, try to use inheritance instead of a lot of very similar classes.