C++ Collision Detection doesn't work on last check? - c++

Over the last few days I have been trying to implement simple collision detection of objects drawn using OpenGL.
With the aid of the Pearson, Computer Graphics with OpenGL I have managed to write the following function:
void move(){
if(check_collision(sprite,platform1) || check_collision(sprite,platform2)){ //if colliding...
if (downKeyPressed ){ y_Vel += speed; downKeyPressed = false;} //going down
else if(upKeyPressed ){ y_Vel -= speed; upKeyPressed = false;} //going up
else if(rightKeyPressed){ x_Vel -= speed; rightKeyPressed = false;} //going right
else if(leftKeyPressed ){ x_Vel += speed; leftKeyPressed = false;} //going left
} // always glitches on whatever is last else if above?!?!
else{ glTranslatef(sprite.x+x_Vel, sprite.y+y_Vel, 0.0); }
}
My sprite moves in accordance to keyboard inputs (the arrow keys). If it collides with a stationary object it stops moving and stays in its position.
So far, it works when colliding with the top, left side and bottom of the stationary object. Unfortunately (even though I use the same logic) the right hand side doesn't work and upon a collision the sprite is redrawn at its original x/y coordinates. I'm baffled.
As it turns out, which-ever is the last check in the move() function (the last else-if) is the one that doesn't work... I have swapped the left with the right and sure enough when left is then the last one and the one that plays up :(
Any advice or ideas on how I can improve this and stop it glitching?
Please excuse my naivety and amateur coding. I'm merely a self-taught beginning. Thanks.

You should not use an else if. There is a possibility that it is hitting a side and the top or the bottom in the same frame. Trying changing those to all ifs because you want to check each one. or at the least change it to this.
if( /* check top */)
{
}
else if( /* check bot */)
{
}
if( /* check right */ )
{
}
else if( /* check left */)
{
}
Also, you should avoid declaring global variables like Y_VEL and X_VEL as this creates confusion. You may just be doing this to get your feet wet but I would avoid it. Create a class for each object and then have the velocities as members of that class.

Well, it seems to me that you have an issue when it comes to translating the actual object.
Your move code states
if(there is a collision)
{
//do stuff
}
else
{
glTranslateF( );
}
SO, whenever there is a collision, the translate function never gets called.
My opinion is that you should pull the glTranslateF() call out of the else {...}, just have it get called every time. However, it seems you're using the exact same 'draw' function for every rectangle, not just the player sprite. You'll probably have to ind a way to distinguish between regular rectangles (such as the platforms) and the player rectangle. Perhaps the simplest way for you to implement this, would be to have two different drawSprite functions: one for regular platforms, and the other for the player. Only call the move() function from within the player's draw function (perhaps called drawPlayer()?)
I don't quite have the time to look over all of your code to make a more educated and specific suggestion at the moment; however, I'll be free later this evening if this question is still open and needing help.

As you've already figured out, the problem is related to glTranslate(). Since you operate on both sprite's position and velocity, you should repeatedly update the positions using the velocities. That is:
sprite.x += x_vel;
sprite.y += y_vel;
and do it simply all the time (i.e. by some timer or every frame, if the scne is redrawn repeatedly). A collision then is equivalent to changing the velocity vector (x_vel, y_vel) in some way to simulate the collision effect: either zero it to stop any movement at all, or change the velocity component sign (x_vel = -x_vel) to make it rebound in an absolutely elastic manner, or do something else that fits.
What happens now with glTranslate() is that x_vel, y_vel actually hold offsets from the starting position, but not velocities of movement.

Related

Proper collision in SFML (C++)

So, I had a test going on to see how collision operates in SFML. I have made this snippet of code:
if (floor.getGlobalBounds().intersects(SuperMario.getGlobalBounds())) // Floor
{
SuperMario.setPosition(SuperMario.getPosition().x, floor.getPosition().y - SuperMario.getOrigin().y);
IsTouching = true;
}
As the code suggests, Mario will change his position when he touches the floor object and will teleport above the floor.
However, this has the following side-effect, illustrated by the pictures below.
Note that the "green box" is the floor object I mentioned earlier. Also, ignore the word "left" in picture 1, I mean "right".
Of course, this behaviour is intended (i.e. is not a bug), but it is unwanted.
So my question is: How can I eliminate this "side-effect"? I mean, how can I modify my code, so Mario will not teleport above the floor, when he touches its sides(making platforming work like a proper platforming)? I want Mario to be stopped by the box, not to be teleported.
UPDATE: So now, I have this:
for (unsigned int i = 0; i <= solidObjects.size() - 1; i++)
{
if (solidObjects[i].getGlobalBounds().intersects(SuperMario.getGlobalBounds()))
{
if (SuperMario.getPosition().x - solidObjects[i].getPosition().x < SuperMario.getPosition().y - solidObjects[i].getPosition().y)
{
SuperMario.setPosition(solidObjects[i].getPosition().x - SuperMario.getOrigin().x, SuperMario.getPosition().y);
IsTouching = false;
}
else if (SuperMario.getPosition().y - solidObjects[i].getPosition().y < SuperMario.getPosition().x - solidObjects[i].getPosition().x)
{
SuperMario.setPosition(SuperMario.getPosition().x, solidObjects[i].getPosition().y - SuperMario.getOrigin().y);
IsTouching = true;
}
else if (SuperMario.getPosition().x - solidObjects[i].getTextureRect().width < SuperMario.getPosition().y - solidObjects[i].getPosition().y)
{
SuperMario.setPosition(solidObjects[i].getTextureRect().width + SuperMario.getOrigin().x, SuperMario.getPosition().y);
IsTouching = false;
}
}
else
{
IsTouching = false;
}
}
However, there is one problem. When Mario touches the sides of the floor, he sticks on them meaning he is unable to move right.
If I am not clear enough, please specify what i should add or clarify more.
This feels really weird, because you'd typically define solid areas rather than those the player can walk inside. You'll want your player to jump after all, rather than having them glued to the ground.
The rest is pretty straightforward:
Iterate over all solid objects and determine whether the player and the solid rectangle overlap.
If they do, determine which distance is smaller (x or y). This lets you determine which axis to move the player.
Determine which direction the player leaves the solid area quicker, i.e. which direction to push the player.
Push the player in the calculated direction and repeat the checks.
Depending on your map complexity this can become rather complex, so you'll most likely want some sorting/spatialisation to reduce the number of comparisons (e.g. skip checking impossible/far away shapes).

Box2d Detect when a body is fully inside another body and which side it came in from

I need to detect when a body is fully inside another body and which side it came in from.
I have balls that bounce around the screen, and can enter the space of other square bodies. I need to know when the ball is fully inside the box, and from which side it came in on. This is NOT just collision detection on a side of the box, as the ball needs to be fully inside the box before anything triggers. I'm using b2FixtureDef::filter::maskBits and b2FixtureDef::filter::categoryBits to allow balls and boxes to not collide with each other.
I'm new to box2d, but not to C++, so I may be missing some functions that could make this easier for me. I started writing the following code, which works when a ball passes the correct edge, but also when it passes other edges.
Is there a way to do this without copying the ball into another data structure that keeps track of where it first contacts the box?
NOTE: This code is an example. It may not actually compile or do exactly what I say it does.
void CBox::captureBalls(std::list<CBall> &balls)
{
std::list<CBall> capturedBalls;
std::list<CBall>::iterator ball = balls.begin();
while (ball != balls.end()) {
bool capture = false;
int ballMinX = ball->getX() - ball->getRadius();
int ballMaxX = ball->getX() + ball->getRadius();
int ballMinY = ball->getY() - ball->getRadius();
int ballMaxY = ball->getY() + ball->getRadius();
switch (this->captureSide) {
case Top:
if ((ballMinX >= this->x) &&
(ballMaxX < (this->x + this->width)) &&
//(ballMinY >= this->y) &&
(ballMaxY < (this->y + this->height)))
capture = true;
break;
case Right:
if (//(ballMinX >= this->x) &&
(ballMaxX < (this->x + this->width)) &&
(ballMinY >= this->y) &&
(ballMaxY < (this->y + this->height)))
capture = true;
break;
case Bottom:
if ((ballMinX >= this->x) &&
(ballMaxX < (this->x + this->width)) &&
(ballMinY >= this->y) /*&&
(ballMaxY < (this->y + this->height))*/)
capture = true;
break;
case Left:
if ((ballMinX >= this->x) &&
//(ballMaxX < (this->x + this->width)) &&
(ballMinY >= this->y) &&
(ballMaxY < (this->y + this->height)))
capture = true;
break;
}
if (capture) {
capturedBalls.push_back(ball);
balls.erase(ball++);
}
else {
++ball;
}
}
}
To detect when a ball is fully inside the box, you could use a sensor fixture inside the box, that is smaller than the box by the diameter of the ball. In the diagram below the black rectangle is the box and the red dashed rectangle is the sensor. (If the balls all have different diameters this would not work.)
As to "which side it came in", I think you need to define what you mean by that, before anyone could help. I mean, look at the possible cases you are dealing with. The blue ball is the most straight-forward in that it approaches on one side in a constant direction. When you detect that it touches the sensor, you could use the direction of travel as suggested by sp2danny, to do a raycast from outside the box to the current position of the ball, and the side it entered is pretty obvious. But this would not work for the green or pink balls. For the pink ball in particular, what side would you consider it entered from?
Now I am assuming that the balls are free to enter the boxes from any angle. But if they had a solid obstruction at their corners, it might be clearer to define which side they came in. You could use four sensors around the exterior, and detect when a ball finishes touching these.
However, it would not be bullet-proof because in rare cases a ball could go from touching one side sensor to another in one time step, without touching nothing in between (green ball). For really fast balls, they could also potentially go from touching one side sensor, to completely inside without ever touching the sensor for the side they "came in" (pink ball). On the plus side though, this would handle the case when you have many different sizes of ball.
Ok... now that I've written up a whole post saying how it can't be done easily, I had a good idea, although it would only work when all balls are the same size. You could use two sensors inside the box, one inset by the radius of the balls, and one inset by the diameter of the balls. When the ball first touches the outer of these sensors, it means the center of the ball has crossed from being outside, to inside the box (but the ball as a whole may not be fully inside). At this point, take a raycast between the previous and current positions, and note which side it intersected. Continue on until the ball also touches the inner sensor, then you know it is fully inside, and you have already noted which side it originally came in from. If the ball stops touching the outer sensor at any point, reset to the starting state.
Note that it is still possible for a ball to first touch the box from one side, then move so that the first time its center is inside the box is from a different side (orange ball). But I am assuming you would not count a mere touch as "came in".

c++ Collision Detection for a turning rectangle

I have some collision detection working when my player hits an object. But this only works when my players x & y co-ordinates hit my marker (which is the centre of my character).
Would making a method returning a vector of all of the coordinates that the players texture cover work and what is the best way to implement this?
This is being done in c++ creating a top down game
There are many ways to do it, most simply is probably(depending on you use of classes etc).
This is the simplest, but no where near the best, or infact very good at all. This way means changing your "marker" to the bottom left of the rectangle.
void collisions()
{
//check if the x-coord is between the furthest left and furthest right x coords
if(rect.Getx() > someObject.Getx() && rect.Getx() < someObject.Getx() + someObject.GetWidth())
{
rect.SetMoveSpeed(0);
}
if(rect.Gety() > someObject.Gety() && rect.Gety() < someObject.Gety() + someObject.GetHeight())
{
rect.setMoveSpeed(0);
}
}
You would then have to set the move speed to normal when it is not colliding. That could be done with an else after each if, setting the move speed again. This is a quick fix and is not recommended for use in a game you plan to distribute anywhere.

Reverse animation direction when hitting the side of the screen

I am creating a space invaders game for my university assignment. I am breaking the parts down on paper, I thought a good place to start would be to move the sprites across the screen. The issue I have at the moment is this, when the sprite his the right hand side of the screen it would just carry on moving, so I added this code:
if (invadersSprite.getPosition().x > 650)
{
std::cout << "WIDTH_END" << std::endl;
}
I basically used this for debugging for future reference. The output popped up into the console so I knew I was onto something. So, I started moving on from the output to actually moving the sprites back to the left hand side of the screen. I am now having more issues then expected.
I declared some ints for up, left, right and down just for easability when it comes to reading the code.
int spriteWalkSpeed = 50;
int up=-spriteWalkSpeed, down=spriteWalkSpeed, left=-spriteWalkSpeed, right=spriteWalkSpeed;
I've tried using the SFML move commands and also setPosition, but none of them really work as I thought they should.
move:
The issue I have had with this one is it basically stops in the middle of the screen. It still animates the leg movement and such, but it doesn't move left or right.
if (invadersSprite.getPosition().x > 650)
{
invadersSprite.move(left, 00);
}
setPosition:
This is a little closer to what I am after, but still no cigar. The movement pauses for around a second and then pops up at the left hand side of the screen. What I need is to move back down the screen.
if (invadersSprite.getPosition().x > 650)
{
invadersSprite.setPosition(left, 00);
}
I haven't been using SFML for very long so I am a little puzzled by this.
EDIT
At the moment the sprite is moving to the right of the screen, as needed:
if(spriteTimer>delay)
{
invadersSprite.setTextureRect(area);
++count;
invadersSprite.move(right,0);
if(count==SPRITECOLS) //WE HAVE MOVED OFF THE RIGHT OF THE IMAGE
{
area.left=0; //reset texture rect at left
count=0; //reset count
}
else
{
area.left+=spaceWidth; //move texture rect right
}
spriteTimer=0; //we have made one move in the sprite tile - start timing for the next move
}
Your current logic will only move the sprite left once if the x-coord is greater than 650 - but that's not exactly what you want. What you want is for the sprite to continuously move left after reaching the edge.
To do this you'll need to keep track of a current velocity for your sprite. For example, when your sprite starts, it will be moving right:
xVelocity = right;
Then you can have 2 conditions that will switch direction (when hitting edges of screen):
if (invaderSprite.getPosition().x >= screenWidth) {
// hit the right side of screen
xVelocity = left;
} else if (invaderSprite.getPosition().x <= 0) {
// hit the left side of screen
xVelocity = right;
}
Now, on ever game tick, you simply move your sprite according to its current velocity:
invaderSprite.move(xVelocity, yVelocity);
There are some other things that will need to be fixed, like taking the width of the sprite into consideration, changing the y velocity, etc., but this is the main idea.

collision of a platformer (like mario bros) not working

i've been sitting here for hours now trying to figure out how collision could work for a platformer.. after doing a lot of research i found something useful in the internet.. but it doesn't work yet :/
my character seems to jump one time.. and then gets stuck a short distance above the ground
This is the function where i load my platforms from txt (by calling setupworld)
in my txt i define xstart (where the platform starts) xend (end of platform) ystart (bottom of platform) 2 unnused variables and the texture filter (0-4 atm)
each platform is then created by repeating 2x2 tiles in x direction
numblocks= number of platforms (sry for the bad variable name ^^)
number of blocks is calculated by taking the end coordinate of the platform - start coordinate and dividing by 2.0 (my platforms always have coordinates dividable by 2.. like.. 0 - 16.. or.. 8 - 16.. )
as u see.. the structure block is where all the data is saved to in setupworld() and it has nothing to do with the number of tiles displayed.. sry again for my weird names
GLvoid BuildLists()
{
texture[0]=LoadPNG("data/grass.png");
texture[1]=LoadPNG("data/gnd.png");
texture[2]=LoadPNG("data/pilz_test.png");
texture[3]=LoadPNG("data/rockwall.png");
texture[4]=LoadPNG("data/crate.png");
setupworld();
quad[0]=glGenLists(numblocks);
for(int loop=0;loop<numblocks;loop++)
{
GLfloat xstart,xend,ystart,u,v,u2,v2;
xstart=block.data[loop].xstart;
xend=block.data[loop].xend;
ystart=block.data[loop].ystart;
//u=block.data[loop].u;
//v=block.data[loop].v;
GLuint filter=block.data[loop].filter;
GLfloat blocks=(xend-xstart)/2.0f;
u=0.0f;
v=0.0f;
u2=1.0f*blocks;
v2=1.0f;
glNewList(quad[loop],GL_COMPILE);
glBindTexture(GL_TEXTURE_2D, texture[filter]);
// Start Drawing Quads
for(int y=0;y<blocks;y++)
{
glBegin(GL_QUADS);
glTexCoord2f(u,v);
glVertex3f(xstart,ystart,-1.0f);
glTexCoord2f(u2,v);
glVertex3f(xstart+((y+1)*2.0f),ystart,-1.0f);
glTexCoord2f(u2,v2);
glVertex3f(xstart+((y+1)*2.0f),ystart+2.0f,-1.0f);
glTexCoord2f(u,v2);
glVertex3f(xstart,ystart+2.0f,-1.0f);
glEnd();
}
glEndList();
quad[loop+1]=quad[loop]+1;
}
}
This is where the key actions are processed..
DetectCollision() calls my function where i (try to) check for collisions
ymovement
ypos2=ypos; is just to remind the last position for repositioning
i jump until i reach 5.0f or a collision in y-direction is detected.. then locky turns TRUE; the else is to let my character get back to ground (cause no gravity) even when the player keeps w pressed
the same thing happens when w is not pressed.. and locky is being reset
xmovement
i add to (or subtract from) xpos for movement
as long as the character doesn't reach the border or a collision appears it should do the normal movement
if (active) // Program Active?
{
if (keys[VK_ESCAPE])
{
done=TRUE;
glDeleteTextures(1,&texture[0]);
glDeleteTextures(1,&texture[2]);
glDeleteTextures(1,&texture[1]);
}
if (keys['W'])
{
if(!locky)
{
DetectCollision();
ypos2=ypos;
ypos=ypos+0.2f;
if(ypos>=5.0f)
{
locky=!locky;
}
if(collisiony)
{
ypos=ypos2;
locky=!locky;
}
}
else
{
if(ypos>0.0f && !collisiony)
{
ypos=ypos-0.2f;
}
}
}
if (!keys['W'])
{
locky=!locky;
if(ypos>0.0f && !collisiony)
{
ypos=ypos-0.2f;
}
}
if (keys['A'])
{
if(xpos>0.0f && !collisionx)
{
xpos=xpos-0.2f;
}
}
if (keys['D'])
{
if(xpos< 50.0f && !collisionx)
{
xpos=xpos+0.2f;
xcam=xcam-0.1f;
}
}
glLoadIdentity();
glTranslatef(0,-7.0f,-25.0f);
DrawWorld(); //draws my platforms by calling the display lists compiled in build lists
DrawChar(); //draws the character
SwapBuffers(hDC);
}
Finally the code where i check for collisions
inPlatformx for checking x
is my character between left and right side of the platform being checked
-> function returns TRUE and is written into collisionx
inPlatformy for checking y
same for inPlatformy
bool inPlatformx(float xpos, BLOCK block, int i){
return xpos > block.data[i].xstart &&
xpos < block.data[i].xend;}
bool inPlatformy(float ypos, BLOCK block, int i){
return ypos > block.data[i].ystart &&
ypos < (block.data[i].ystart+0.2);
}
GLvoid DetectCollision(){
for(int i=0; i<numblocks;i++)
{
collisionx=inPlatformx(xpos,block,i);
collisiony=inPlatformy(ypos,block,i);
}
}
finally a screenshot
http://www.grenzlandzocker.de/test.png
I hope u can help me.. either fix my code or give me some tips on collisions.. since it's my first game with opengl :s
if u need any more detail or infos please ask ^^
and thanks in advance !
if (keys['W'])
{
//DetectCollision();
if(!locky)
{
ypos2=ypos;
ypos=ypos+0.2f;
if(ypos>=5.0f)
{
locky=!locky;
}
if(collisiony)
{
ypos=ypos2;
locky=!locky;
}
}
else
{
if(ypos>0.0f)
{
ypos=ypos-0.2f;
}
}
}
if (!keys['W'])
{
locky=!locky;
if(ypos>0.0f && !collisiony)
{
ypos=ypos-0.2f;
}
}
if (keys['A'])
{
//DetectCollision();
if(xpos>0.0f && !collisionx)
{
xpos2=xpos;
xpos=xpos-0.2f;
}
if(collisionx)
{
xpos=xpos2;
}
}
if (keys['D'])
{
//DetectCollision();
if(xpos< 50.0f && !collisionx)
{
xpos2=xpos;
xpos=xpos+0.2f;
xcam=xcam-0.1f;
}
if(collisionx)
{
xpos=xpos2;
}
}
THANKS :)
well i just edited the code for x movement and collision.. so it works properly.. (despite the flickering (but idc atm :) ).. i'm wondering why jumping doesn't work at all anymore.. it's just increasing till i'm stuck.. can't even get up once anymore :/
i put my detectCollision() in front of they key section.. which works for x AND y now (hopefully)..
and i also edited something in DetectCollision()
i had ystart+0.2 instead of ystart+2.0 which is the correct coordinate for the platforms top
but looks like it just got worse at y
i'm still totally confused..
oh and talking about those predefined api's and stuff.. since somebody first showed me some things with glut i tried to make the next step and initialize everything myself.. i guess detection is much easier using predefined stuff.. but i want to learn it and not just get one game to work :)
if u have any more suggestions for my code i would be really grateful.. and if u know any good books for starters till advanced lvl i would really appreciate
and yes.. i know.. display lists are deprecated since opengl 3.0 ^^
Unless I am not following your code correcty, once you reach the apex of your jump and set your locky to !locky, you start hitting your else statement, which never checks for collision. IF you are moving in the x or -x direction, you likely want to be doing this as the ground may not be in the same place as your origin of the jump.
Additionally, your locky check is checking if the ypos >= 5.0f , which will immediately be the case if you are already on some part of your game world above the 5.0 mark. You likely want this to be a variable such as limitY = ypos + 5.0f; and then check if ypos >= limitY, so it works regardless of origin.
As for the issue you are seeing now, it should be easy to debug and look at the current value of your y coordinate and see if there is anything obvious (such as not executing a final ypos -= 0.2f ) which is cause for you floating slightly above the ground after a jump. (I don't see an obvious error in the way you are doing your code, although I would not have designed it in the way you are doing it yourself.)
If you are developing this for Windows you may want to look into XNA development, which makes collision detection and resolution a lot easier.
Are you initializing locky to true or false? because all the code i can see inverts the state of locky, so depending on how the input is processed, your locky value is flipping every loop or possibly being set out of sync with your expectations.
I would recommend setting locky to true and false explicitly in the code you've shown, rather than using locky=!locky, it's clearer about the state of the system.