Friday, July 6, 2018

c++ - Collision rectangle response


I'm having difficulties getting a moveable rectangle to collide with more than one rectangle.



I'm using SFML and it has a handy function called intersects which takes 2 rectangles and returns the intersections. I have a vector full of rectangles which I want my moveable rectangle to collide with. I'm looping through this using the following code (p is the moveble rectangle).


IsCollidingWith returns a bool but also uses SFML's intersects to work out the intersections.


while(unsigned i = 0; i!= testRects.size(); i++){
if(p.IsCollidingWith(testRects[i]){
p.Collide(testRects[i]);
}
}

and the actual Collide() code:


void gameObj::collide( gameObj collidingObject ){


printf("%f %f\n", this->colliderResult.width, this->colliderResult.height);

if (this->colliderResult.width < this->colliderResult.height) {
// collided on X
if (this->getCollider().left < collidingObject.getCollider().left ) {
this->move( -this->colliderResult.width , 0);
}else {
this->move( this->colliderResult.width, 0 );
}


}

if(this->colliderResult.width > this->colliderResult.height){
if (this->getCollider().top < collidingObject.getCollider().top ) {
this->move( 0, -this->colliderResult.height);
}else {
this->move( 0, this->colliderResult.height );
}


}

and the IsCollidingWith() code is:


bool gameObj::isCollidingWith( gameObj testObject ){
if (this->getCollider().intersects( testObject.getCollider(), this->colliderResult )) {
return true;
}else {
return false;
}


This works fine when there's only 1 Rect in the scene. However, when there's more than one Rect it causes an issue when working out 2 collisions at once.


Any idea how to deal with this correctly? I have uploaded a video to youtube to show my problem. The console on the far-right shows the width and height of the intersections. You can see on the console that it's trying to calculate 2 collisions at once, I think this is where the problem is being caused.


Finally, the image below seems to illustrate my problem nicely:


rectangle colliding with multiple other rectangles




No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...