Collision detection, how is it done? (SFML, if that matters)

Whether you're a newbie or an experienced programmer, any questions, help, or just talk of any language will be welcomed here.

Moderator: Coders of Rage

myInt
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 10
Joined: Thu Sep 30, 2010 9:36 am

Collision detection, how is it done? (SFML, if that matters)

Post by myInt »

I've searched this forum, I've searched the internet but nothing has helped. Either I'm retarded or it's just that the topics I've found has gotten answers that are a little bit too advanced for me.

So, how is it done? I'm making a very simple pong game as my very first game in SFML. I have 2 rackets and a ball. That shouldn't be too hard, right?

What I do know is is that you have to somehow give the coordinates of the ball's position and the rackets's positions to variables that stores them, or something like that. That's how far I have come. But how do I do it?
User avatar
StoveBacon
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 98
Joined: Mon Sep 20, 2010 6:09 pm
Favorite Gaming Platforms: PC Xbox360 SNES N64
Programming Language of Choice: c++

Re: Collision detection, how is it done? (SFML, if that matters)

Post by StoveBacon »

I've never used SFML but i'm sure the concept is exactly the same.
You're going to want to make a "rectangle" containing the x,y,width, and height of the sprites that you will pass to a function that checks for collision.
For the "rectangle" you could just use a struct:

Code: Select all

struct Rectangle
{
    int x,y,w,h;
}
OR you could just pass the coordinates (x y w h) to the function manually( might take less time but is more messy).
the way you check for collision is something like this

Code: Select all

bool collision(x1,y1,w1,h1,x2,y2,w2,h2); //function definition
//then later...
bool collision(x1,y1,w1,h1,x2,y2,w2,h2)
{
    if(x1 < x2 + w2 && x1 + w1 > x2 && y1 < y2 + h2 && y1 + h1 > y2)
       {
          return true;
        }
       return false;
}
and if you don't understand the way the rectangle works, x represents the LEFT side of the rectangle, y represents the TOP, x + width is the RIGHT, and y + height is the BOTTOM.
hope I helped.
SeaNanners wrote:"I shall be Vince Bonesteel and you will be....Rick McLightning!"
Day[9] wrote:"Read a book to children. Mass genocide. Lunch. The life of Dr. Seuss himself."
User avatar
Lord Pingas
Chaos Rift Regular
Chaos Rift Regular
Posts: 178
Joined: Thu Dec 31, 2009 9:33 am
Favorite Gaming Platforms: NES, SNES, Nintendo 64, Dreamcast, Wii
Programming Language of Choice: C++
Location: Hiding In My Mum's Basement With My Pokemon Cards

Re: Collision detection, how is it done? (SFML, if that matters)

Post by Lord Pingas »

The most basic form of collision is using bounding boxes...
Basically you just want to check if two rectangles are intersecting.

Let's say you have a Rectangle struct/class...
It has 4 attributes; the x position, y position, the width and the height.

You could then create a boolean isColliding() function that takes two Rectangle objects as parameters...

Code: Select all

bool isColliding(Rectangle rectA, Rectangle rectB) {
    if(rectA.x < rectB.x + rectB.width) //if the right side of rectA is touching left side rectB
        return true;
    if(rectA.x + rectA.width > rectB.x) //if left side of RectA is touching right rectB
        return true;
    if(rectA.y < rectB.y + height) //if top of rectA if touching bottom of rectB
        return true;
    if(rectA.y + height > rectB.y) //if bottom of rectA is touching top of rectB
        return true;

    //if none of the sides are touching...
    return false;
}
Now using the collision function, we can check if two rectangles are colliding! :)

Code: Select all

if(isCollision(rectPlayer, rectEnemy))
    //do something...
User avatar
avansc
Respected Programmer
Respected Programmer
Posts: 1708
Joined: Sun Nov 02, 2008 6:29 pm

Re: Collision detection, how is it done? (SFML, if that matters)

Post by avansc »

Myeah, that does not work at all....

The simplest collision is to see if circles/spears intersect.

if (A-B)^2 < A.radius^2 + B.radius^2 then collision.

obviously dont use pow or sqrt, so its something like

if( (A.x-B.x)*(A.x-B.x) + (A.y-B.y)*(A.y-B.y) < A.r*A.r + B.r*B.r )
{
// collision
}

and if you want to do rectangles, then make sure your data structure is center + and - the width and height.

this way you can add the width and height to the other rect, and it becomes a point in rect, which is much simpler.

assuming you have rect A and B

if(A.x > B.x - B.w- A.w && A.x < B.x + B.w + A.w && A.y > B.y - B.h- A.h && A.y < B.y + B.h + A.h)
{
//collision
}
Some person, "I have a black belt in karate"
Dad, "Yea well I have a fan belt in street fighting"
myInt
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 10
Joined: Thu Sep 30, 2010 9:36 am

Re: Collision detection, how is it done? (SFML, if that matters)

Post by myInt »

I'm still learning C++ so I have a question. Do I write all of the code that you have written or do I choose one of them? I don't really follow...

Thanks for the answer!
User avatar
StoveBacon
Chaos Rift Cool Newbie
Chaos Rift Cool Newbie
Posts: 98
Joined: Mon Sep 20, 2010 6:09 pm
Favorite Gaming Platforms: PC Xbox360 SNES N64
Programming Language of Choice: c++

Re: Collision detection, how is it done? (SFML, if that matters)

Post by StoveBacon »

myInt wrote:I'm still learning C++ so I have a question. Do I write all of the code that you have written or do I choose one of them? I don't really follow...
for my solution you'd want to take

Code: Select all

 bool collision(x1,y1,w1,h1,x2,y2,w2,h2)
before your main function you will have the deceleration of the function, and if you don't know what a function is or how to use it then i heavily suggest you go back and learn some more c++ before trying to work on a game.

Code: Select all

bool collision(x1,y1,w1,h1,x2,y2,w2,h2); //decleration
and if you are checking between say player 1 and the ball you would put something like this

Code: Select all

int main()
{
   //game loop
   if(collision(playerx ,playery ,playerw ,playerh ,ballx ,bally ,ballw ,ballh ) = true);
   {
       //stuff to do when they collide such as move the ball in the opposite direction
   }
then after the main function you would have:

Code: Select all

bool collision(x1,y1,w1,h1,x2,y2,w2,h2)
{
    if(x1 < x2 + w2 && x1 + w1 > x2 && y1 < y2 + h2 && y1 + h1 > y2)
       {
          return true;
        }
       return false;
}
so to start off with, after you write all of your #includes and stuff, before your main function, you want to write the function definition that takes the x, y, w, h of two objects.

in the main function during your game loop, your going to want to test for collision by writing in the function definition but instead of just x1,y1 etc, you would use the values you assign to your paddle and ball.

and after the main function...
passing the x , y, w, h of both the player and the ball to the collision function will check if the two objects are colliding and return a true or false.
hope i helped.
and again as i said, if you don't understand how functions work, try working into your c++ some more.

http://www.cprogramming.com/tutorial/lesson4.html
this is a pretty useful tutorial (and website) were you can learn about functions and other c++ stuff.
SeaNanners wrote:"I shall be Vince Bonesteel and you will be....Rick McLightning!"
Day[9] wrote:"Read a book to children. Mass genocide. Lunch. The life of Dr. Seuss himself."
User avatar
Van-B
Chaos Rift Regular
Chaos Rift Regular
Posts: 125
Joined: Tue Aug 10, 2010 7:17 am
Current Project: iPhone puzzle game
Favorite Gaming Platforms: All - Except Amiga
Programming Language of Choice: DBPro, ObjC++
Location: Scotland

Re: Collision detection, how is it done? (SFML, if that matters)

Post by Van-B »

One method I like, is to do an exclusion condition check - or whatever it might be called, give it your own name :D.
Anyway...
Imagine you have 2 rectangular areas, A and B, and you might have a struct so each area can have variables, although rather than A.x,A.y etc, I prefer A.l, A.r, A.t, A.b - for left, right top and bottom.

Then try to dis-proove that the rectangles overlap...psuedo code of course.
Collision=true
If A.l > B.r then Collision = false
If A.r < B.l then Collision = false
If A.t > B.b then Collision = false
If A.b < B.t then Collision = false

In C++ you would use returns, so it would be pretty fast, as what it's looking for is an exclusion, it's looking for reasons why the rectangles do not overlap, rather than trying to proove that they do. One benefit in this technique is that it makes the condition checks much more straightforward - for instance what if rectanble B is fully enclosed inside rectangle A? - quite tricky to detect that, but this technique can detect that because it's an overlap check. Usually, I would make a function that takes the X and Y coordinate of both rectangles plus a size - which will be used to calculate the left right, top etc - although it would work for any size and proportioned rectangles, I'm guessing square on square sprite collision is your first priority.
Health, ammo.... and bacon and eggs.
myInt
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 10
Joined: Thu Sep 30, 2010 9:36 am

Re: Collision detection, how is it done? (SFML, if that matters)

Post by myInt »

Thanks for all of the answers!

I understood some of it but unfortunatley I don't really understand. I do know about functions, classes and such but I should learn a little more about passing variables for this, I see now. But eventually, I'll get there. And I'll try again ;).

Edit:
Let me refrase the question.

Is there a way for me to assign a position to for example the ball when it's moving? I mean, can I have a variable that "knows" exactly where the ball is?
User avatar
GroundUpEngine
Chaos Rift Devotee
Chaos Rift Devotee
Posts: 835
Joined: Sun Nov 08, 2009 2:01 pm
Current Project: mixture
Favorite Gaming Platforms: PC
Programming Language of Choice: C++
Location: UK

Re: Collision detection, how is it done? (SFML, if that matters)

Post by GroundUpEngine »

myInt wrote:Is there a way for me to assign a position to for example the ball when it's moving? I mean, can I have a variable that "knows" exactly where the ball is?
? ;)

Code: Select all

class Ball {
  public:
    int PositionX, PositionY;     // Refer to these variables for the Ball's position
   
    sf::Rect BoundingBox;         // For collision checks against this Ball
    bool Collision(Rect& entity); // For collision checks against other Ball's or Paddle's
};
myInt
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 10
Joined: Thu Sep 30, 2010 9:36 am

Re: Collision detection, how is it done? (SFML, if that matters)

Post by myInt »

GroundUpEngine wrote:
myInt wrote:Is there a way for me to assign a position to for example the ball when it's moving? I mean, can I have a variable that "knows" exactly where the ball is?
? ;)

Code: Select all

class Ball {
  public:
    int PositionX, PositionY;     // Refer to these variables for the Ball's position
   
    sf::Rect BoundingBox;         // For collision checks against this Ball
    bool Collision(Rect& entity); // For collision checks against other Ball's or Paddle's
};
I googled "rect" and it seems that you have to download something since it's not in SFML. And I'm too lazy to download something. ;)

Thanks anyways! I suppose there are no "easy" ways for this. But that's good. That makes me do at least a little "real" programming. I actually think SFML and such is kind of cheating. :P
User avatar
dandymcgee
ES Beta Backer
ES Beta Backer
Posts: 4709
Joined: Tue Apr 29, 2008 3:24 pm
Current Project: https://github.com/dbechrd/RicoTech
Favorite Gaming Platforms: NES, Sega Genesis, PS2, PC
Programming Language of Choice: C
Location: San Francisco
Contact:

Re: Collision detection, how is it done? (SFML, if that matters)

Post by dandymcgee »

myInt wrote: I googled "rect" and it seems that you have to download something since it's not in SFML. And I'm too lazy to download something. ;)

Thanks anyways! I suppose there are no "easy" ways for this. But that's good. That makes me do at least a little "real" programming. I actually think SFML and such is kind of cheating. :P
http://www.sfml-dev.org/documentation/1 ... _1Rect.htm
Rect is an SFML class. This was the first result of the google query "sfml rect". I'm curious.. what exactly did you search for?
Falco Girgis wrote:It is imperative that I can broadcast my narcissistic commit strings to the Twitter! Tweet Tweet, bitches! :twisted:
User avatar
GroundUpEngine
Chaos Rift Devotee
Chaos Rift Devotee
Posts: 835
Joined: Sun Nov 08, 2009 2:01 pm
Current Project: mixture
Favorite Gaming Platforms: PC
Programming Language of Choice: C++
Location: UK

Re: Collision detection, how is it done? (SFML, if that matters)

Post by GroundUpEngine »

myInt wrote: I googled "rect" and it seems that you have to download something since it's not in SFML. And I'm too lazy to download something. ;)

Thanks anyways! I suppose there are no "easy" ways for this. But that's good. That makes me do at least a little "real" programming. I actually think SFML and such is kind of cheating. :P
lol
dandymcgee wrote: http://www.sfml-dev.org/documentation/1 ... _1Rect.htm
Rect is an SFML class. This was the first result of the google query "sfml rect". I'm curious.. what exactly did you search for?
just what I was thinking ;)
myInt
Chaos Rift Newbie
Chaos Rift Newbie
Posts: 10
Joined: Thu Sep 30, 2010 9:36 am

Re: Collision detection, how is it done? (SFML, if that matters)

Post by myInt »

First I tried to write the code. And my compiler said: "argument for class type "sf::rect" is missing". I don't know exactly what that means but I assumed that it wasn't an SFML class. Then I searched for "rect c++" and found something that had written in the code "#include <rect>".

But appearently it is SFML.

May I ask what it does?

Does someone know of any good SFML tutorials? I've tried a few but none of them has been very good, really. They teach you a little about the stuff and such but they don't show you what it can do in practice, you know? And that's a boring way to learn. If someone knows about a goof tutorial that teaches me to make some kind of simple game, please tell me.
User avatar
EccentricDuck
Chaos Rift Junior
Chaos Rift Junior
Posts: 305
Joined: Sun Feb 21, 2010 11:18 pm
Current Project: Isometric "2.5D" Airship Game
Favorite Gaming Platforms: PS2, SNES, GBA, PC
Programming Language of Choice: C#, Python, JScript
Location: Edmonton, Alberta

Re: Collision detection, how is it done? (SFML, if that matters)

Post by EccentricDuck »

To the OP, don't worry about collision detection for now. Play around with moving something around and keeping track of it's position. Try this:
- Make a class called ball with two public fields - "x" and "y". Give them default values of 0 in the constructor.
- Write a function called DisplayPosition() in that class that writes x and y to the console window (probably using "cout"). // I'm assuming you don't know how to draw to the screen yet
- Make a game class with three fields - "finished" (boolean), "input"(Input class from SFML***), and "ball" (Ball class you just wrote). Give finished a default value of false and create objects of Input and Ball in the constructor. // *** go to this link and read about input: http://www.sfml-dev.org/documentation/1 ... 1Input.htm
- In your game class, write a while loop with the parameter being "finished == false". Inside that while loop, write six if statements with the condition being Input.IsKeyDown(// your key code in here //). To the first four, write the key codes for the up, down, left, and right arrows. Inside them, write code that increases or decreases the ball object's x or y values. To the fifth, make it whatever key you want. Inside it's going to call the ball's DisplayPosition() function. To the sixth, do the same but make it something like "x", "q", or "esc". To this one, you're going to make it change the value of finished to true. It'll quit your game by ending the while loop (and taking you to the end of the main() function).

Save, compile, and run. Assuming I didn't forget something (which is very well possible), you should be able to increase or decrease the ball's x or y values with the arrow keys, check them with whatever key you set for that, and quit the game with "x", "q", or "esc". That should give you a good starting point to play around with whatever you want to do next (probably using a rect struct to instead of x and y position coordinates).
User avatar
GroundUpEngine
Chaos Rift Devotee
Chaos Rift Devotee
Posts: 835
Joined: Sun Nov 08, 2009 2:01 pm
Current Project: mixture
Favorite Gaming Platforms: PC
Programming Language of Choice: C++
Location: UK

Re: Collision detection, how is it done? (SFML, if that matters)

Post by GroundUpEngine »

EccentricDuck wrote:To the OP, don't worry about collision detection for now. Play around with moving something around and keeping track of it's position.
Very good advice.
Post Reply