oliver18
oliver18

Reputation: 11

Android: RectF and collision detection not functioning

I am using two RectFs on my 2 game objects in order to detect a collision between them.

Here are the two lines setting up the RectFs:

RectF playerRect = new RectF((x-0.1f), (y+0.1f), (x+0.1f), (y-0.1f));
RectF asteroidRect = new RectF((asteroidX-0.1f), (asteroidY+0.1f), (asteroidX+0.1f), (asteroidY-0.1f));

and here is the collision detection for them:

if(playerRect.intersect(asteroidRect)) {
    asteroidY = 1.15f;
    asteroidX = randomAsteroidX / 100;
}

the values x and y are the player's x and y positions. the values asteroidX and asteroidY are the asteroid's position. It is my understand that using a RectF should set up a rectangle around the player and another around the asteroid of width and height 0.2f using the values I have provided. With these values however, the hit detection (intersect) does not work. Have I set up the RectF wrong? Any ideas?

Upvotes: 1

Views: 785

Answers (1)

hb22
hb22

Reputation: 383

According to https://developer.android.com/reference/android/graphics/RectF.html :

RectF(float left, float top, float right, float bottom)

I may be wrong as I have not seen how you have set up your players and asteroids previously, but it looks as though you have mistakenly switched this for

RectF(float left, float bottom, float right, float top)

If this is the case:

Try switching to

RectF playerRect = new RectF((x-0.1f), (y-0.1f), (x+0.1f), (y+0.1f));
RectF asteroidRect = new RectF((asteroidX-0.1f), (asteroidY-0.1f),(asteroidX+0.1f), (asteroidY+0.1f));

Upvotes: 1

Related Questions