How to handle collision in SFML
Page 1 of 111 Replies - 4815 Views - Last Post: 03 September 2011 - 11:48 AM
#1
How to handle collision in SFML
Posted 31 August 2011 - 12:34 PM
Thanks
XeVile
Replies To: How to handle collision in SFML
#2
Re: How to handle collision in SFML
Posted 31 August 2011 - 12:43 PM
#3
Re: How to handle collision in SFML
Posted 31 August 2011 - 05:44 PM
They do however have this code sample which implements bounding boxes, bounding circles and pixel perfect collision detection.
Your other option if you need something more advanced is to implement a 2D physics system like Box2D.
#4
Re: How to handle collision in SFML
Posted 31 August 2011 - 09:06 PM
Serapth, on 31 August 2011 - 05:44 PM, said:
They do however have this code sample which implements bounding boxes, bounding circles and pixel perfect collision detection.
Your other option if you need something more advanced is to implement a 2D physics system like Box2D.
So, I have to make/include a precreated collision header file everytime I implement collision?
Isn't there an easier method for implementing collision.
This post has been edited by XeVile: 31 August 2011 - 09:07 PM
#5
Re: How to handle collision in SFML
Posted 01 September 2011 - 09:53 AM
#6
Re: How to handle collision in SFML
Posted 01 September 2011 - 01:44 PM
#7
Re: How to handle collision in SFML
Posted 02 September 2011 - 02:45 AM
stayscrisp, on 01 September 2011 - 01:44 PM, said:
Sorry
Well I tried again and this time I didnt try the sample test but tried my own. here is the error I got:-
1>SFML_Test.obj : error LNK2019: unresolved external symbol "public: static bool __cdecl Collision::BoundingBoxTest(class sf::Sprite const &,class sf::Sprite const &)" (?BoundingBoxTest@Collision@@SA_NABVSprite@sf@@0@Z) referenced in function _main 1>C:\Users\Arunabh\Documents\Visual Studio 2008\Projects\SFML_Test\Debug\SFML_Test.exe : fatal error LNK1120: 1 unresolved externals
here is the code used:-
#include "resource.h"
#include <SFML/Graphics.hpp>
#include "Collision.h"
using namespace sf;
Image image;
Sprite sprite;
Image image2;
Sprite sprite2;
Collision::Collision() {
}
Collision::~Collision() {
}
int main()
{
// Create the main rendering window
RenderWindow App(VideoMode(800, 600, 32), "SFML Graphics");
if(!image.LoadFromFile("sprite.png"))
return 1;
if(!image2.LoadFromFile("sprite2.png"))
return 1;
sprite.SetImage(image);
sprite2.SetImage(image2);
sprite.SetCenter(16, 16);
sprite.SetPosition(400, 300);
sprite2.SetCenter(32, 8);
sprite2.SetPosition(350, 300);
// Start game loop
while (App.IsOpened())
{
// Process events
Event eEvent;
while (App.GetEvent(eEvent))
{
// Close window : exit
if (eEvent.Type == Event::Closed)
App.Close();
if((eEvent.Type == Event::KeyPressed) && (eEvent.Key.Code == Key::Right))
sprite.Rotate(-20.0f);
if((eEvent.Type == Event::KeyPressed) && (eEvent.Key.Code == Key::Left))
sprite.Rotate(+20.0f);
if(Collision::BoundingBoxTest(sprite, sprite2))
sprite.SetPosition(0,0);
}
// Clear the screen (fill it with black color)
App.Clear(Color(0, 180, 255));
App.Draw(sprite);
App.Draw(sprite2);
// Display window contents on screen
App.Display();
}
return EXIT_SUCCESS;
}
Here is the collision.h file code:-
/*
* File: collision.h
* Author: Nick Koirala
*
* Collision Detection and handling class
* For SFML.
(c) 2009 - LittleMonkey Ltd
This software is provided 'as-is', without any express or
implied warranty. In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, and to alter it and redistribute
it freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented;
you must not claim that you wrote the original software.
If you use this software in a product, an acknowledgment
in the product documentation would be appreciated but
is not required.
2. Altered source versions must be plainly marked as such,
and must not be misrepresented as being the original software.
3. This notice may not be removed or altered from any
source distribution.
*
* Created on 30 January 2009, 11:02
*/
#ifndef _COLLISION_H
#define _COLLISION_H
#ifndef PI
#define PI (3.14159265358979323846)
#endif
#define RADIANS_PER_DEGREE (PI/180.0)
class Collision {
public:
virtual ~Collision();
/**
* Test for a pixel perfect collision detection between
* two Sprites, Rotation and Scale is supported in this test
*
* @param Object1 The first sprite
* @param Object2 The second sprite
* @AlphaLimit How opaque a pixel needs to be before a hit it registered
*/
static bool PixelPerfectTest(const sf::Sprite& Object1 ,const sf::Sprite& Object2, sf::Uint8 AlphaLimit = 127);
/**
* Test for collision using circle collision dection
* Radius is averaged from the dimesnions of the sprite so
* roughly circular objects will be much more accurate
*/
static bool CircleTest(const sf::Sprite& Object1, const sf::Sprite& Object2);
/**
* Test for bounding box collision using OBB Box.
* To test against AABB use PixelPerfectTest with AlphaLimit = 0
*
* @see Collision::PixelPerfectTest
*/
static bool BoundingBoxTest(const sf::Sprite& Object1, const sf::Sprite& Object2);
/**
* Generate a Axis-Aligned Bounding Box for broad phase of
* Pixel Perfect detection.
*
* @returns IntRect to round off Floating point positions.
*/
static sf::IntRect GetAABB(const sf::Sprite& Object);
/**
* Helper function in order to rotate a point by an Angle
*
* Rotation is CounterClockwise in order to match SFML Sprite Rotation
*
* @param Point a Vector2f representing a coordinate
* @param Angle angle in degrees
*/
static sf::Vector2f RotatePoint(const sf::Vector2f& Point, float Angle);
/**
* Helper function to get the minimum from a list of values
*/
static float MinValue(float a, float b, float c, float d);
/**
* Helper function to get the maximum from a list of values
*/
static float MaxValue(float a, float b, float c, float d);
private:
Collision();
};
#endif /* _COLLISION_H */
This post has been edited by XeVile: 02 September 2011 - 02:59 AM
#8
Re: How to handle collision in SFML
Posted 02 September 2011 - 01:32 PM
This post has been edited by stayscrisp: 03 September 2011 - 02:55 AM
Reason for edit:: No need to quote the huge post above you
#9
Re: How to handle collision in SFML
Posted 02 September 2011 - 08:47 PM
1>Collision.cpp 1>c:\users\arunabh\documents\visual studio 2008\projects\sfml_test\sfml_test\collision.cpp(118) : warning C4244: 'argument' : conversion from 'int' to 'float', possible loss of data 1>c:\users\arunabh\documents\visual studio 2008\projects\sfml_test\sfml_test\collision.cpp(118) : warning C4244: 'argument' : conversion from 'int' to 'float', possible loss of data 1>c:\users\arunabh\documents\visual studio 2008\projects\sfml_test\sfml_test\collision.cpp(119) : warning C4244: 'argument' : conversion from 'int' to 'float', possible loss of data 1>c:\users\arunabh\documents\visual studio 2008\projects\sfml_test\sfml_test\collision.cpp(119) : warning C4244: 'argument' : conversion from 'int' to 'float', possible loss of data 1>SFML_Test.cpp 1>c:\users\arunabh\documents\visual studio 2008\projects\sfml_test\sfml_test\collision.cpp(118) : warning C4244: 'argument' : conversion from 'int' to 'float', possible loss of data 1>c:\users\arunabh\documents\visual studio 2008\projects\sfml_test\sfml_test\collision.cpp(118) : warning C4244: 'argument' : conversion from 'int' to 'float', possible loss of data 1>c:\users\arunabh\documents\visual studio 2008\projects\sfml_test\sfml_test\collision.cpp(119) : warning C4244: 'argument' : conversion from 'int' to 'float', possible loss of data 1>c:\users\arunabh\documents\visual studio 2008\projects\sfml_test\sfml_test\collision.cpp(119) : warning C4244: 'argument' : conversion from 'int' to 'float', possible loss of data 1>Generating Code... 1>Linking... 1>SFML_Test.obj : error LNK2005: "private: __thiscall Collision::Collision(void)" (??0Collision@@AAE@XZ) already defined in Collision.obj 1>SFML_Test.obj : error LNK2005: "public: virtual __thiscall Collision::~Collision(void)" (??1Collision@@UAE@XZ) already defined in Collision.obj 1>SFML_Test.obj : error LNK2005: "public: static class sf::Rect<int> __cdecl Collision::GetAABB(class sf::Sprite const &)" (?GetAABB@Collision@@SA?AV?$Rect@H@sf@@ABVSprite@3@@Z) already defined in Collision.obj 1>SFML_Test.obj : error LNK2005: "public: static float __cdecl Collision::MinValue(float,float,float,float)" (?MinValue@Collision@@SAMMMMM@Z) already defined in Collision.obj 1>SFML_Test.obj : error LNK2005: "public: static float __cdecl Collision::MaxValue(float,float,float,float)" (?MaxValue@Collision@@SAMMMMM@Z) already defined in Collision.obj 1>SFML_Test.obj : error LNK2005: "public: static class sf::Vector2<float> __cdecl Collision::RotatePoint(class sf::Vector2<float> const &,float)" (?RotatePoint@Collision@@SA?AV?$Vector2@M@sf@@ABV23@M@Z) already defined in Collision.obj 1>SFML_Test.obj : error LNK2005: "public: static bool __cdecl Collision::PixelPerfectTest(class sf::Sprite const &,class sf::Sprite const &,unsigned char)" (?PixelPerfectTest@Collision@@SA_NABVSprite@sf@@0E@Z) already defined in Collision.obj 1>SFML_Test.obj : error LNK2005: "public: static bool __cdecl Collision::CircleTest(class sf::Sprite const &,class sf::Sprite const &)" (?CircleTest@Collision@@SA_NABVSprite@sf@@0@Z) already defined in Collision.obj 1>SFML_Test.obj : error LNK2005: "public: static bool __cdecl Collision::BoundingBoxTest(class sf::Sprite const &,class sf::Sprite const &)" (?BoundingBoxTest@Collision@@SA_NABVSprite@sf@@0@Z) already defined in Collision.obj 1>C:\Users\Arunabh\Documents\Visual Studio 2008\Projects\SFML_Test\Debug\SFML_Test.exe : fatal error LNK1169: one or more multiply defined symbols found 1>Build log was saved at "file://c:\Users\Arunabh\Documents\Visual Studio 2008\Projects\SFML_Test\SFML_Test\Debug\BuildLog.htm"
Here is the code of the Collision.cpp file:-
/*
* File: collision.cpp
* Author: Nick
*
* Created on 30 January 2009, 11:02
*/
#include <SFML/Graphics.hpp>
#include "Collision.h"
Collision::Collision() {
}
Collision::~Collision() {
}
sf::IntRect Collision::GetAABB(const sf::Sprite& Object) {
//Get the top left corner of the sprite regardless of the sprite's center
//This is in Global Coordinates so we can put the rectangle back into the right place
sf::Vector2f pos = Object.TransformToGlobal(sf::Vector2f(0, 0));
//Store the size so we can calculate the other corners
sf::Vector2f size = Object.GetSize();
float Angle = Object.GetRotation();
//Bail out early if the sprite isn't rotated
if (Angle == 0.0f) {
return sf::IntRect(static_cast<int> (pos.x),
static_cast<int> (pos.y),
static_cast<int> (pos.x + size.x),
static_cast<int> (pos.y + size.y));
}
//Calculate the other points as vectors from (0,0)
//Imagine sf::Vector2f A(0,0); but its not necessary
//as rotation is around this point.
sf::Vector2f B(size.x, 0);
sf::Vector2f C(size.x, size.y);
sf::Vector2f D(0, size.y);
//Rotate the points to match the sprite rotation
B = RotatePoint(B, Angle);
C = RotatePoint(C, Angle);
D = RotatePoint(D, Angle);
//Round off to int and set the four corners of our Rect
int Left = static_cast<int> (MinValue(0.0f, B.x, C.x, D.x));
int Top = static_cast<int> (MinValue(0.0f, B.y, C.y, D.y));
int Right = static_cast<int> (MaxValue(0.0f, B.x, C.x, D.x));
int Bottom = static_cast<int> (MaxValue(0.0f, B.y, C.y, D.y));
//Create a Rect from out points and move it back to the correct position on the screen
sf::IntRect AABB = sf::IntRect(Left, Top, Right, Bottom);
AABB.Offset(static_cast<int> (pos.x), static_cast<int> (pos.y));
return AABB;
}
float Collision::MinValue(float a, float b, float c, float d) {
float min = a;
min = (b < min ? b : min);
min = (c < min ? c : min);
min = (d < min ? d : min);
return min;
}
float Collision::MaxValue(float a, float b, float c, float d) {
float max = a;
max = (b > max ? b : max);
max = (c > max ? c : max);
max = (d > max ? d : max);
return max;
}
sf::Vector2f Collision::RotatePoint(const sf::Vector2f& Point, float Angle) {
Angle = Angle * RADIANS_PER_DEGREE;
sf::Vector2f RotatedPoint;
RotatedPoint.x = Point.x * cos(Angle) + Point.y * sin(Angle);
RotatedPoint.y = -Point.x * sin(Angle) + Point.y * cos(Angle);
return RotatedPoint;
}
bool Collision::PixelPerfectTest(const sf::Sprite& Object1, const sf::Sprite& Object2, sf::Uint8 AlphaLimit) {
//Get AABBs of the two sprites
sf::IntRect Object1AABB = GetAABB(Object1);
sf::IntRect Object2AABB = GetAABB(Object2);
sf::IntRect Intersection;
if (Object1AABB.Intersects(Object2AABB, &Intersection)) {
//We've got an intersection we need to process the pixels
//In that Rect.
//Bail out now if AlphaLimit = 0
if (AlphaLimit == 0) return true;
//There are a few hacks here, sometimes the TransformToLocal returns negative points
//Or Points outside the image. We need to check for these as they print to the error console
//which is slow, and then return black which registers as a hit.
sf::IntRect O1SubRect = Object1.GetSubRect();
sf::IntRect O2SubRect = Object2.GetSubRect();
sf::Vector2i O1SubRectSize(O1SubRect.GetWidth(), O1SubRect.GetHeight());
sf::Vector2i O2SubRectSize(O2SubRect.GetWidth(), O2SubRect.GetHeight());
sf::Vector2f o1v;
sf::Vector2f o2v;
//Loop through our pixels
for (int i = Intersection.Left; i < Intersection.Right; i++) {
for (int j = Intersection.Top; j < Intersection.Bottom; j++) {
o1v = Object1.TransformToLocal(sf::Vector2f(i, j)); //Creating Objects each loop :(/>
o2v = Object2.TransformToLocal(sf::Vector2f(i, j));
//Hack to make sure pixels fall withint the Sprite's Image
if (o1v.x > 0 && o1v.y > 0 && o2v.x > 0 && o2v.y > 0 &&
o1v.x < O1SubRectSize.x && o1v.y < O1SubRectSize.y &&
o2v.x < O2SubRectSize.x && o2v.y < O2SubRectSize.y) {
//If both sprites have opaque pixels at the same point we've got a hit
if ((Object1.GetPixel(static_cast<int> (o1v.x), static_cast<int> (o1v.y)).a > AlphaLimit) &&
(Object2.GetPixel(static_cast<int> (o2v.x), static_cast<int> (o2v.y)).a > AlphaLimit)) {
return true;
}
}
}
}
return false;
}
return false;
}
bool Collision::CircleTest(const sf::Sprite& Object1, const sf::Sprite& Object2) {
//Simplest circle test possible
//Distance between points <= sum of radius
float Radius1 = (Object1.GetSize().x + Object1.GetSize().y) / 4;
float Radius2 = (Object2.GetSize().x + Object2.GetSize().y) / 4;
float xd = Object1.GetPosition().x - Object2.GetPosition().x;
float yd = Object1.GetPosition().y - Object2.GetPosition().y;
return sqrt(xd * xd + yd * yd) <= Radius1 + Radius2;
}
//From Rotated Rectangles Collision Detection, Oren Becker, 2001
bool Collision::BoundingBoxTest(const sf::Sprite& Object1, const sf::Sprite& Object2) {
sf::Vector2f A, B, C, BL, TR;
sf::Vector2f HalfSize1 = Object1.GetSize();
sf::Vector2f HalfSize2 = Object2.GetSize();
//For somereason the Vector2d divide by operator
//was misbehaving
//Doing it manually
HalfSize1.x /= 2;
HalfSize1.y /= 2;
HalfSize2.x /= 2;
HalfSize2.y /= 2;
//Get the Angle we're working on
float Angle = Object1.GetRotation() - Object2.GetRotation();
float CosA = cos(Angle * RADIANS_PER_DEGREE);
float SinA = sin(Angle * RADIANS_PER_DEGREE);
float t, x, a, dx, ext1, ext2;
//Normalise the Center of Object2 so its axis aligned an represented in
//relation to Object 1
C = Object2.GetPosition();
C -= Object1.GetPosition();
C = RotatePoint(C, Object2.GetRotation());
//Get the Corners
BL = TR = C;
BL -= HalfSize2;
TR += HalfSize2;
//Calculate the vertices of the rotate Rect
A.x = -HalfSize1.y*SinA;
B.x = A.x;
t = HalfSize1.x*CosA;
A.x += t;
B.x -= t;
A.y = HalfSize1.y*CosA;
B.y = A.y;
t = HalfSize1.x*SinA;
A.y += t;
B.y -= t;
t = SinA * CosA;
// verify that A is vertical min/max, B is horizontal min/max
if (t < 0) {
t = A.x;
A.x = B.x;
B.x = t;
t = A.y;
A.y = B.y;
B.y = t;
}
// verify that B is horizontal minimum (leftest-vertex)
if (SinA < 0) {
B.x = -B.x;
B.y = -B.y;
}
// if rr2(ma) isn't in the horizontal range of
// colliding with rr1(r), collision is impossible
if (B.x > TR.x || B.x > -BL.x) return false;
// if rr1(r) is axis-aligned, vertical min/max are easy to get
if (t == 0) {
ext1 = A.y;
ext2 = -ext1;
}// else, find vertical min/max in the range [BL.x, TR.x]
else {
x = BL.x - A.x;
a = TR.x - A.x;
ext1 = A.y;
// if the first vertical min/max isn't in (BL.x, TR.x), then
// find the vertical min/max on BL.x or on TR.x
if (a * x > 0) {
dx = A.x;
if (x < 0) {
dx -= B.x;
ext1 -= B.y;
x = a;
} else {
dx += B.x;
ext1 += B.y;
}
ext1 *= x;
ext1 /= dx;
ext1 += A.y;
}
x = BL.x + A.x;
a = TR.x + A.x;
ext2 = -A.y;
// if the second vertical min/max isn't in (BL.x, TR.x), then
// find the local vertical min/max on BL.x or on TR.x
if (a * x > 0) {
dx = -A.x;
if (x < 0) {
dx -= B.x;
ext2 -= B.y;
x = a;
} else {
dx += B.x;
ext2 += B.y;
}
ext2 *= x;
ext2 /= dx;
ext2 -= A.y;
}
}
// check whether rr2(ma) is in the vertical range of colliding with rr1(r)
// (for the horizontal range of rr2)
return !((ext1 < BL.y && ext2 < BL.y) ||
(ext1 > TR.y && ext2 > TR.y));
}
SFML_Test.cpp
#include "resource.h"
#include <SFML/Graphics.hpp>
#include "Collision.h"
#include "Collision.cpp"
using namespace sf;
Image image;
Sprite sprite;
Image image2;
Sprite sprite2;
int main()
{
// Create the main rendering window
RenderWindow App(VideoMode(800, 600, 32), "SFML Graphics");
if(!image.LoadFromFile("sprite.png"))
return 1;
if(!image2.LoadFromFile("sprite2.png"))
return 1;
sprite.SetImage(image);
sprite2.SetImage(image2);
sprite.SetCenter(16, 16);
sprite.SetPosition(400, 300);
sprite2.SetCenter(32, 8);
sprite2.SetPosition(350, 300);
// Start game loop
while (App.IsOpened())
{
// Process events
Event eEvent;
while (App.GetEvent(eEvent))
{
// Close window : exit
if (eEvent.Type == Event::Closed)
App.Close();
if((eEvent.Type == Event::KeyPressed) && (eEvent.Key.Code == Key::Right))
sprite.Rotate(-20.0f);
if((eEvent.Type == Event::KeyPressed) && (eEvent.Key.Code == Key::Left))
sprite.Rotate(+20.0f);
}
// Clear the screen (fill it with black color)
App.Clear(Color(0, 180, 255));
App.Draw(sprite);
App.Draw(sprite2);
// Display window contents on screen
App.Display();
}
return EXIT_SUCCESS;
}
Collision.h file still has the same code.
#10
Re: How to handle collision in SFML
Posted 02 September 2011 - 08:52 PM
#11
Re: How to handle collision in SFML
Posted 02 September 2011 - 09:45 PM
1>LINK : fatal error LNK1000: Internal error during IncrBuildImage 1> Version 9.00.21022.08 1> ExceptionCode = C0000005 1> ExceptionFlags = 00000000 1> ExceptionAddress = 00000000 (00000000) "f:\Microsoft Visual Studio 9.0\VC\bin\link.exe" 1> NumberParameters = 00000002 1> ExceptionInformation[ 0] = 00000008 1> ExceptionInformation[ 1] = 00000000 1>CONTEXT: 1> Eax = 00000000 Esp = 001CF080 1> Ebx = 40008158 Ebp = 001CF0AC 1> Ecx = 00FCD670 Esi = 40059720 1> Edx = 001CF09C Edi = 0100D6C0 1> Eip = 00000000 EFlags = 00010246 1> SegCs = 0000001B SegDs = 00000023 1> SegSs = 00000023 SegEs = 00000023 1> SegFs = 0000003B SegGs = 00000000 1> Dr0 = 00000000 Dr3 = 00000000 1> Dr1 = 00000000 Dr6 = 00000000 1> Dr2 = 00000000 Dr7 = 00000000 1>Build log was saved at "file://c:\Users\Arunabh\Documents\Visual Studio 2008\Projects\SFML_Test\SFML_Test\Debug\BuildLog.htm"
#12
Re: How to handle collision in SFML
Posted 03 September 2011 - 11:48 AM
Possible solution.
|
|

New Topic/Question
Reply



MultiQuote






|