c++ game

I am trying to do collision detection in my c++ game.

I have defined the sprite that the user is going to control like this in the header

AnimatedSprite( const Image& Img, const Vector2f& Position = Vector2f(0, 0), const Vector2f& Scale = Vector2f(1, 1), float Rotation = 0.f, const Color& Col = Color(255, 255, 255, 255),int xCount=2,int yCount=2);

I was thinking that I could use the xCount and yCount to do collsion detection.

I want to check for collisions with sprites that are on a scroller

I have attached my main below to show everyone what I am working with.

I was thinking that I need to use an IF statement that checks the yCount and xCount against the scroller sprites. But I dont know how I would go about doing this. Any ideas?
#include <SFML/Graphics.hpp>
#include <SFML/System.hpp>
#include <iostream>
#include <sstream>
#include "ScrollSprite.h"
#include "Scroller.h"
#include "AnimatedSprite.h"
#include "powerupScroller.h"
using std::endl;
int main()
{

	//initialisation - lots of this code could be put into functions for 
	//neatness and separation of concerns. You need to declare objects here to draw them
	//but the set up for those objects could be done in a function or a class

	//window dimensions 
	unsigned int width=600;
	unsigned int height=480;
	
	//we need a timer to update things - get a clock
	sf::Clock clock;
	static float timeAccumulator=0.0;
    
	//load resources for the scroller - images and sounds (if you have any)	
	sf::Image backGround;
	if(!backGround.LoadFromFile("images/backGrnd2.jpg")) std::cout<<"File not found background.jpg"<<std::endl;

    sf::Image title;
	if(!title.LoadFromFile("images/title.png")) std::cout<<"File not found title.jpg"<<std::endl;
	
	sf::Image aScroll;	
	if(!aScroll.LoadFromFile("images/rock.png")) std::cout<<"File not found rock.png"<<std::endl;

    sf::Image bScroll;	
	if(!bScroll.LoadFromFile("images/navalmine.png")) std::cout<<"File not found navalmine.png"<<std::endl;

    sf::Image cScroll;	
	if(!cScroll.LoadFromFile("images/barrel.png")) std::cout<<"File not found barrel.png"<<std::endl;

    sf::Image dScroll;	
	if(!dScroll.LoadFromFile("images/ship.png")) std::cout<<"File not found ship.png"<<std::endl;

    sf::Image aNimat;	
	if(!aNimat.LoadFromFile("images/sub.png")) std::cout<<"File not found sub.png"<<std::endl;

	//resouces loaded
    int level = 0;
	int lives = 3;
   

   	AnimatedSprite anim(aNimat,Vector2f(0,-20),Vector2f(1,1),0,Color(255,255,255,255),10,10);
	
	//resouces loaded
	anim.Scale(3,3);
	
    
   
	anim.setInterval(1.05);
	anim.Move(200,200);
    
	
	sf::Sprite backGndSprite(backGround);
	backGndSprite.Scale(0.75f,0.8f);

    sf::Sprite screen(title);
	screen.Scale(0.75f,0.8f);

	

	//set up the scroller data
	ScrollSprite scrollingSprite(dScroll);
	scrollingSprite.setScrollPos(10);
	scrollingSprite.setVertPos(300);

	Scrollpower scrollingSprite0(cScroll);
	scrollingSprite0.setScrollPos(10);
	scrollingSprite0.setVertPos(300);
	

	ScrollSprite scrollingSprite1(aScroll);
	scrollingSprite1.setScrollPos(30);
	scrollingSprite1.setVertPos(320);

	ScrollSprite scrollingSprite2(aScroll);
	scrollingSprite2.setScrollPos(30);
	scrollingSprite2.setVertPos(380);
	scrollingSprite2.SetScale(3,3);

	ScrollSprite scrollingSprite3(cScroll);
	scrollingSprite3.setScrollPos(500);
	scrollingSprite3.setVertPos(400);
	scrollingSprite3.SetScale(1,1);
	
	ScrollSprite scrollingSprite4(aScroll);
	scrollingSprite4.setScrollPos(710);
	scrollingSprite4.setVertPos(300);

	ScrollSprite scrollingSprite5(bScroll);
	scrollingSprite5.setScrollPos(930);
	scrollingSprite5.setVertPos(20);

	ScrollSprite scrollingSprite6(aScroll);
	scrollingSprite6.setScrollPos(1100);
	scrollingSprite6.setVertPos(380);
	scrollingSprite6.SetScale(3,3);

	ScrollSprite scrollingSprite7(aScroll);
	scrollingSprite7.setScrollPos(1300);
	scrollingSprite7.setVertPos(4000);
	scrollingSprite7.SetScale(3,3);

    ScrollSprite scrollingSprite8(bScroll);
	scrollingSprite8.setScrollPos(1300);
	scrollingSprite8.setVertPos(4000);
	scrollingSprite8.SetScale(3,3);

    ScrollSprite scrollingSprite9(bScroll);
	scrollingSprite9.setScrollPos(1300);
	scrollingSprite9.setVertPos(4000);
	scrollingSprite9.SetScale(3,3);

    ScrollSprite scrollingSprite10(bScroll);
	scrollingSprite10.setScrollPos(1300);
	scrollingSprite10.setVertPos(35);
	scrollingSprite10.SetScale(1,1);

    ScrollSprite scrollingSprite11(bScroll);
	scrollingSprite11.setScrollPos(1300);
	scrollingSprite11.setVertPos(4000);
	scrollingSprite11.SetScale(3,3);

    ScrollSprite scrollingSprite12(bScroll);
	scrollingSprite12.setScrollPos(1300);
	scrollingSprite12.setVertPos(4000);
	scrollingSprite12.SetScale(3,3);

    ScrollSprite scrollingSprite13(bScroll);
	scrollingSprite13.setScrollPos(1300);
	scrollingSprite13.setVertPos(100);
	scrollingSprite13.SetScale(1,1);

    ScrollSprite scrollingSprite14(bScroll);
	scrollingSprite14.setScrollPos(1300);
	scrollingSprite14.setVertPos(4000);
	scrollingSprite14.SetScale(3,3);

    ScrollSprite scrollingSprite15(bScroll);
	scrollingSprite15.setScrollPos(1700);
	scrollingSprite15.setVertPos(20);
	scrollingSprite15.SetScale(1,1);

    ScrollSprite scrollingSprite16(cScroll);
	scrollingSprite16.setScrollPos(30);
	scrollingSprite16.setVertPos(320);
	scrollingSprite16.SetScale(1,1);

    ScrollSprite scrollingSprite17(dScroll);
    scrollingSprite17.setScrollPos(500);
	scrollingSprite17.setVertPos(400);
	scrollingSprite17.SetScale(1,1);


	std::vector<ScrollSprite*> pSprite;
	pSprite.push_back(&scrollingSprite);
	pSprite.push_back(&scrollingSprite1);
	pSprite.push_back(&scrollingSprite2);
	pSprite.push_back(&scrollingSprite3);
	pSprite.push_back(&scrollingSprite4);
	pSprite.push_back(&scrollingSprite5);
	pSprite.push_back(&scrollingSprite6);
	pSprite.push_back(&scrollingSprite7);
	pSprite.push_back(&scrollingSprite8);
	pSprite.push_back(&scrollingSprite9);
	pSprite.push_back(&scrollingSprite10);
	pSprite.push_back(&scrollingSprite11);
	pSprite.push_back(&scrollingSprite12);
	pSprite.push_back(&scrollingSprite13);
	pSprite.push_back(&scrollingSprite14);
    pSprite.push_back(&scrollingSprite15);
    pSprite.push_back(&scrollingSprite16);
    //pSprite.push_back(&scrollingSprite17); 





  
	//nb - scroller window width needs to match window size
	
    Scroller scr(2000,width,pSprite,400);
	
   

    
	// Create main window
    sf::RenderWindow App(sf::VideoMode(width, height), "Scroller Window"); 
	
    // Start the display loop
    while (App.IsOpened())
    {
		
		sf::Event Event;
          
		//check inputs in the event queue
				 while (App.GetEvent(Event))
				{
					// Close window : exit
					if (Event.Type == sf::Event::Closed)
						App.Close();
					// Escape key : exit
					if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Escape))
						App.Close();

					//up arrow key : does nothing
					if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Up))
					{
                        
                        
					    anim.Move(0,-20);
						//to do something on up key write here
												
					}

	                if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::Down))
					{
                        
                       anim.Move(0,20);
						//to do something on up key write here
												
					}

                     if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::S))
					
					{
                        
					 screen.Rotate(100.00);
					}

                     if ((Event.Type == sf::Event::KeyPressed) && (Event.Key.Code == sf::Key::W))
					
					{
                        
					 anim.Rotate(30.00);
					}

					
					
					//other events are ignored
				}

				 //update the things that need updating in the game loop

				 float f=clock.GetElapsedTime();
				 clock.Reset();
				 timeAccumulator+=f;
				 scr.update(f);
				 anim.update(f);
				 

				 //draw the things you have to draw
                  
				  App.Draw(backGndSprite);
				  App.Draw(anim);
                  App.Draw(scr);
                  App.Draw(screen);
                 
				

				 //Monitoring the display function
				std::stringstream str;
				 str<<"The display rate is ";		
				 
				 str<<1/f;
				 //str<<"  the accumulated time is "<<timeAccumulator;
                 str<<1/f;
				 std::string s;
				 std::getline(str,s);
				 str.clear();				 
				 sf::String TextScore(s.c_str(),sf::Font::GetDefaultFont(),15);
					TextScore.SetPosition(0,0);
					TextScore.SetColor(sf::Color(255, 0, 0));
					App.Draw(TextScore);

                 std::stringstream stv;
				 stv<<"The level is "<<level;
				 //stv<<1/f;
				 std::string sv;
				 std::getline(stv,sv);
				 stv.clear();
				 sf::String Text(sv.c_str(),sf::Font::GetDefaultFont(),15);
				 Text.SetPosition(10,20);
				 Text.SetColor(sf::Color(255,0,0));
				 App.Draw(Text);


			     std::stringstream stvt;
				 stvt<<"The distance travelled "<<timeAccumulator<<"Mps";
				 stv<<1/f;
				 std::string sx;
				 std::getline(stvt,sx);
				 stvt.clear();
				 sf::String Dist(sx.c_str(),sf::Font::GetDefaultFont(),15);
				 Dist.SetPosition(20,30);
				 Dist.SetColor(sf::Color(255,0,0));
				 App.Draw(Dist);


                 std::stringstream stvs;
				 stvs<<"LIVES "<<lives;
				 //stvs<<1/f;
				 std::string sm;
				 std::getline(stvs,sm);
				 stvt.clear();
				 sf::String life(sm.c_str(),sf::Font::GetDefaultFont(),15);
				 life.SetPosition(20,40);
				 life.SetColor(sf::Color(255,0,0));
				 App.Draw(life);
				  
				if (timeAccumulator > 10)

				{

				      level = 1;
                     
					 
					 

				}

               
	            if (timeAccumulator > 50)

				{

				      level = 2;
                      
					 

				}


                if (timeAccumulator > 100)

				{

				      level = 3;
                      
					  

				}


				if (level > 1)

				{
                  
				}
                  
				


			
					
			
        // Finally, display the rendered frame on screen
        App.Display();
    }

    
    return EXIT_SUCCESS;

}

Open in new window

tango2009Asked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ZoppoCommented:
Hi tango2009,

here you can find an article describing different collision-detection mechanisms with code samples: http://www.gamedev.net/reference/articles/article735.asp

Hope that helps,

ZOPPO
tango2009Author Commented:
I have looked at the page you suggested and the first example will be sufficient. So I want to use the two values at the end of this code

AnimatedSprite anim(aNimat,Vector2f(0,-20),Vector2f(1,1),0,Color(255,255,255,255),10,10);

The two tens at the end. These two values are the xCount and the yCount however how do I take these values and put them into another int so I can use them in an IF statement. Is this even possible?
tango2009Author Commented:
This is how animated sprtie is defined

AnimatedSprite( const Image& Img, const Vector2f& Position = Vector2f(0, 0), const Vector2f& Scale = Vector2f(1, 1), float Rotation = 0.f, const Color& Col = Color(255, 255, 255, 255),int xCount=2,int yCount=2);
Become a Microsoft Certified Solutions Expert

This course teaches how to install and configure Windows Server 2012 R2.  It is the first step on your path to becoming a Microsoft Certified Solutions Expert (MCSE).

ZoppoCommented:
What exactly are the 'xCount' and 'yCount' used for?

To use the mentioned algorithm you'll have to calculate the bounding box for all sprites you want to test for collision, so you need their position (the vector 'Position') and size (which IMO is any initial value, i.e. the size of the image, multiplied with the vector 'Scale').

Now, since I have no idea what the both 'count' variables are used for I'm not sure if they can be used to solve this - if they contain the original size of the sprite you can use them, if they don't have to do anything with that initial size IMO you can't ...

ZOPPO
tango2009Author Commented:
Oh sorry I have just realised  I am talking about the wrong part.

 This part of the code is the size of the image

Vector2f(5,1)

and this vector is the position of the sprite

Vector2f(0,-50)


In this part of the code

      AnimatedSprite anim(aNimat,Vector2f(0,-50),Vector2f(5,1),0,Color(255,255,255,255),9,5);

This is how the position is defined in the header

AnimatedSprite( const Image& Img, const Vector2f& Position = Vector2f(0, 0), const Vector2f& Scale = Vector2f(1, 1), float Rotation = 0.f, const Color& Col = Color(255, 255, 255, 255),int xCount=2,int yCount=2);

can I use these two vectors in an IF statement?



ZoppoCommented:
Well, so if I understand you correctly each sprite simly has the bounding box where left/top is 'Position' and right/bottom is 'Position' + 'Scale', right?

So you could simply use this - calculate the bounding boxes of the two (or more) wanted sprites from these two values and use it as shown in the code from the above mentioned site ...
tango2009Author Commented:
I am on the right track at the moment

so far I have used this code from the example


    int left1, left2;
      int right1, right2;
      int top1, top2;
      int bottom1, bottom2;

      left1 = Vector2f->x;
      left2 = object2->x;
      right1 = Vector2f->x + vector2f->width;
        right2 = object2->x + object2->width;
        top1 = vector2f->y;
        top2 = object2->y;
        bottom1 = vector2f->y + vector2f->height;
        bottom2 = object2->y + object2->height;


Am I right that in the example object1 is one bounding box and object2 is the other sprite that you want to check collisions with?

So how can I create a bounding box for one of the scrolling sprites? This would go in the place of object2 in the code above.

my scrolling sprites are like this

       ScrollSprite scrollingSprite(dScroll);
      scrollingSprite.setScrollPos(10);
      scrollingSprite.setVertPos(300);
ZoppoCommented:
Both 'object1' and 'object2' from the sample are objects which represant one sprite - each of them has a position (x, y) and a size (width, height).

I'm not really sure what's the different with your 'setScrollPos' and 'setVertPos', but I guess one is to set horizontal and the other one to set vertical position, right?

Maybe best would be to implement a function to retrieve the boundaries for a sprite in your sprite-class, i.e.:

void
ScrollSprite::CalcBoundingRect( int& left, int& right, int& top, int& bottom )
{
 // I'm not sure about which members/functions you have to use here, maybe somehow like this (if some of these functions are missing you should implement them):
 left = getScrollPos();
 top = getVertPos();
 right = left + getWidth();
 bottom = top + getHeight();
}

Then you could do someting like this:

bool
ScrollSprite::DetectCollision( ScrollSprite& otherSprite )
{
 int left1, top1, right1, bottom1;
 int left2, top2, right2, bottom2;

 CalcBoundingRect( left1, right1, top1, bottom1 );
 otherSprite.CalcBoundingRect( left2, right2, top2, bottom2 );

 // this is from the sample code
 if (bottom1 < top2) return false;
 if (top1 > bottom2) return false;

 if (right1 < left2) return false;
 if (left1 > right2) return false;

 return true;
}

Hope that helps,

ZOPPO
tango2009Author Commented:
I have different classes for my animated sprite and the scrolling sprites should I add the two functions to the scrolling sprite class and then just call the other sprite.
ZoppoCommented:
Best would be you could implement this in a base class of all sprite classes in a generic way, at least the 'CalcBoundingRect'.

Then about the DetectCollision you can even think about implementing somewhere esle - i.e. instead of using a container 'std::vector<ScrollSprite*>' you could implement a class which is a manager/container for the sprites; then you could there, somehow like this:

bool
SpriteManager::DetectCollision( ScrollSprite& spriteA, ScrollSprite& spriteB ) // or better pass base class of all sprite classes here
{
 int left1, top1, right1, bottom1;
 int left2, top2, right2, bottom2;

 spriteA.CalcBoundingRect( left1, right1, top1, bottom1 );
 spriteB.CalcBoundingRect( left2, right2, top2, bottom2 );
 ... // same as above
tango2009Author Commented:
So I need to create a new class and header called SpriteManager which is for the all the sprites.

When I come to do the detectcollision part how can I take the Scrollsprite and test it against the animatedsprite

could I do it like this

ScrollSprite::CalcBoundingRect( int& left, int& right, int& top, int& bottom )
{
 // I'm not sure about which members/functions you have to use here, maybe somehow like this (if some of these functions are missing you should implement them):
 left = getScrollPos();
 top = getVertPos();
 right = left + getWidth();
 bottom = top + getHeight();
}

animatedSprite::CalcBoundingRect( int& left, int& right, int& top, int& bottom )
{
 // I'm not sure about which members/functions you have to use here, maybe somehow like this (if some of these functions are missing you should implement them):
 left = vector2f();
 top = vector2f();
 right = left + getWidth();
 bottom = top + getHeight();
}

bool
ScrollSprite::DetectCollision( ScrollSprite& animatedSprite )
{
 int left1, top1, right1, bottom1;
 int left2, top2, right2, bottom2;

 CalcBoundingRect( left1, right1, top1, bottom1 );
 animatedsprite.CalcBoundingRect( left2, right2, top2, bottom2 );

 // this is from the sample code
 if (bottom1 < top2) return false;
 if (top1 > bottom2) return false;

 if (right1 < left2) return false;
 if (left1 > right2) return false;

 return true;
}
ZoppoCommented:
Do the classes 'ScrollSprite' and 'animatedSprite' have similar base class or is one derived by the other or are they anyhow related?

BTW, you don't really 'need to create a new class ... SpriteManager' - it's just an idea, depending on your needs it might be a good one or not. IMO it often is senseful to encapsulate all functionality one wants to execute onto a set of objects within such a manager/container class.
tango2009Author Commented:
Thats my problem they are not related. Would it be best to rewrite my sprite class to something simpler and that clearly defines the boundaries of the sprite?
ZoppoCommented:
Well, I guess this would be a good idea since I guess they have some related functionality.

There aren't many arguments against implementing this with a base class using virtual functions except you want/need to avoid that your objects use virtual functions at all.

If this is not the case it would be simple to implement a base class as shown in the attached code (in this sample you even don't need to change your existing classes).

With this you can at any time call 'DetectCollision' in any combination for both classes, i.e.:

> ScrollSprite sp;
> animatedSprite ap;
> bool b1 = sp.DetectCollision( ap );
> bool b2 = ap.DetectCollision( sp );

ZOPPO
// in header
class SpriteBase
{
 public:
  virtual void CalcBoundingRect( int& left, int& right, int& top, int& bottom ) = 0; // abstract class
  bool DetectCollision( SpriteBase& otherSprite );
};

// derive your classes from SpriteBase
class ScrollSprite : public SpriteBase
{
public:
  virtual void CalcBoundingRect( int& left, int& right, int& top, int& bottom );
// ...
};

class animatedSprite : public SpriteBase
{
public:
  virtual void CalcBoundingRect( int& left, int& right, int& top, int& bottom );
// ...
};


// in cpp file
bool SpriteBase::DetectCollision( SpriteBase& otherSprite )
{
 int left1, top1, right1, bottom1;
 int left2, top2, right2, bottom2;

 CalcBoundingRect( left1, right1, top1, bottom1 );
 otherSprite.CalcBoundingRect( left2, right2, top2, bottom2 );

 // this is from the sample code
 if (bottom1 < top2) return false;
 if (top1 > bottom2) return false;

 if (right1 < left2) return false;
 if (left1 > right2) return false;

 return true;
}

// use the 'CalcBoundingRect' functions for both derived classes as you posted them above
ScrollSprite::CalcBoundingRect( int& left, int& right, int& top, int& bottom )
{
 left = getScrollPos();
 top = getVertPos();
 right = left + getWidth();
 bottom = top + getHeight();
}

animatedSprite::CalcBoundingRect( int& left, int& right, int& top, int& bottom )
{
 left = vector2f();
 top = vector2f();
 right = left + getWidth();
 bottom = top + getHeight();
}

Open in new window

ZoppoCommented:
Sorry, there are missing two 'void's:
> void ScrollSprite::CalcBoundingRect ...
> void animatedSprite::CalcBoundingRect ...
tango2009Author Commented:
I have added the animatedSprite::CalcBoundRect and the ScrollSprite::CalcBoundingRect into the AnimatedSprite class and the ScrollSprite class is this right or should they go into the the SpriteBase class and then call them in the other two classes?
ZoppoCommented:
No, that's ok if you made it as I posted (declare it as virtual at least in 'SpriteBase' and don't forget the '= 0;' at the end of the declaration.

Thus you tell the compiler the class 'SpriteBase' is an abstract class and you have to implement this function in any derived class - whenever you call this function for a 'SpriteBase' derived object its own function gets called (as it's done in 'DetectCollection')
ZoppoCommented:
This is the nice thing with implementing it like this - each derived class can use its own method to calculate its bounding box - if you i.e. anywhen will have to implement circle-shaped sprites you can override the 'CalcBoundRect' in order to calculate the bounding box from the center point and the radius.
tango2009Author Commented:
Should I include spritebase.h in both my animatedsprite class and my spritebase class. At the moment it seems to saying that all the variables and everthing are not defined now.


I will post my animatedsprite.cpp to show what I am doing and if I am doing it right

#include "AnimatedSprite.h"
#include "Spritebase.h"


AnimatedSprite::AnimatedSprite() : Sprite()
{
}
		
AnimatedSprite::AnimatedSprite(const Image& Img, const Vector2f& Position, const Vector2f& Scale , float Rotation, const Color& Col ,int xTiles,int yTiles)
{
	tilesWide=xTiles;
	tilesHigh=yTiles;
	numTiles=xTiles*yTiles;
	currentTile=0;
	stepTime=1.0;
	for(int i=0;i<numTiles;i++)
	{	
	sf::Sprite* mySprite=new Sprite(Img,Position,Scale,Rotation);
	mySprite->SetSubRect(IntRect(calculateColIndex(i)*(Img.GetWidth()/xTiles),calculateRowIndex(i)*(Img.GetHeight()/yTiles),(calculateColIndex(i)+1)*(Img.GetWidth()/xTiles),(calculateRowIndex(i)+1)*(Img.GetHeight()/yTiles)));
	tiles.push_back(mySprite);
	}
	accumulator=0;
	isVisible=true;
	
}

AnimatedSprite::~AnimatedSprite()
{
	std::vector<Sprite*>::iterator it;
		for(it=tiles.begin();it!=tiles.end();++it)
		{
			delete *it;
			*it=0;
		}
}
void AnimatedSprite::update(float dt)
{
	if(isVisible)
	{
		accumulator+=dt;
		if(accumulator>stepTime) 
		{
			accumulator-=stepTime;
			currentTile=(currentTile+1)%numTiles;
		}
	}
}
void AnimatedSprite::Render (const RenderWindow &Window) const 
{
	if(isVisible)	Window.Draw(*tiles.at(currentTile));
}
	
int AnimatedSprite::calculateRowIndex(int cT) const
{
	return cT/tilesWide;
}

int AnimatedSprite::calculateColIndex(int cT) const
{
	return cT - tilesWide*calculateRowIndex(cT);
}

void AnimatedSprite::start()
{
	isVisible=true;
}
void AnimatedSprite::stop()
{
	isVisible=false;
}
void AnimatedSprite::setInterval(float stepTime)
{
	this->stepTime=stepTime;
}

bool AnimatedSprite::getVisibility()
{
	return isVisible;
}

virtual void AnimatedSprite::CalcBoundingRect( int& left, int& right, int& top, int& bottom )
{
 left = vector2f();
 top = vector2f();
 right = left + getWidth();
 bottom = top + getHeight();
}

Open in new window

ZoppoCommented:
You'll have to include the 'SpriteBase.h' either in the derived classes header files befor the class declaration or within each cpp file before the includes for any derived classes header. I prefer the first one (include it in any header before declaration of the derived class) since you won't have to take care if you later include a derived class's header anywhere else.

So, if you use it similar to my last code sample you need i.e. include it like this in 'ScrollSprite's header

> #include "SpriteBase.h"
> class ScrollSprite : public SpriteBase
> ...

Some questions if you still have problems:

- which variables aren't defined for example?
- what class is 'Sprite'? Is it a base class you already had?
- could you post your 'SpriteBase.h' and 'AnimatedSprite.h'?

ZOPPO
tango2009Author Commented:
I will add my claases that I am working with to show you where I am going wrong with this. i have an awful lot of errors in my code now.
classes.zip
ZoppoCommented:
Some of the code I gave you was just for example. So with just copying it into your project had to fail.

The class 'Sprit' is one you include from anywhere else, right? If so IMO it would be senseful to derive 'SpriteBase' from 'Sprite' and then derive all other sprites from 'SpriteBase'

I'll post the files as I think you have to modify them as attachmenst - unfortunateley I can't compile it here so I just hope I make no failures.


First file here is 'SpriteBase.h'


ZOPPO
#ifndef SPRITE_BASE_H
#define SPRITE_BASE_H
#include <SFML/Graphics.hpp>
using namespace sf;

class SpriteBase : public Sprite
{
 public:
  SpriteBase();
  virtual void CalcBoundingRect( int& left, int& right, int& top, int& bottom ) = 0; // abstract class
  bool DetectCollision( SpriteBase& otherSprite );
};

#endif

Open in new window

tango2009Author Commented:
I have changed the headers to what you said above and it seems to be giving me even more errors.

I have changed the start of the headers like this

#ifndef SCROLL_SPRITE_H
#define SCROLL_SPRITE_H
#include <SFML/Graphics.hpp>
using namespace sf;
#include "Spritebase.h"

class ScrollSprite : public Spritebase
{
public:
ZoppoCommented:
Here comes 'SpriteBase.cpp'
#include "Spritebase.h"

SpriteBase::SpriteBase():Sprite()
{
}

bool SpriteBase::DetectCollision( SpriteBase& otherSprite )
{
 int left1, top1, right1, bottom1;
 int left2, top2, right2, bottom2;

 CalcBoundingRect( left1, right1, top1, bottom1 );
 otherSprite.CalcBoundingRect( left2, right2, top2, bottom2 );

 // this is from the sample code
 if (bottom1 < top2) return false;
 if (top1 > bottom2) return false;

 if (right1 < left2) return false;
 if (left1 > right2) return false;

 return true;
}

Open in new window

ZoppoCommented:
Here is 'AnimatedSprite.h'
#ifndef ANIMATED_SPRITE_H
#define ANIMATED_SPRITE_H
#include <SFML/Graphics.hpp>
#include <vector>
using namespace sf;

#include "SpriteBase.h"

//an animated sprite - works from an image containing a set of tiles 
class AnimatedSprite : public SpriteBase
{
public:

	AnimatedSprite();
	AnimatedSprite( const Image& Img, const Vector2f& Position = Vector2f(0, 0), const Vector2f& Scale = Vector2f(1, 1), float Rotation = 0.f, const Color& Col = Color(255, 255, 255, 255),int xCount=2,int yCount=2);
	void update(float dt);//updates the animatiion by time dt
	virtual ~AnimatedSprite();//a destructor - we are using the heap
	void start();//starts the animation (by default the animation is started automatically)
	void stop();//stops the animation
	void setInterval(float stepTime);//the tick time for moving through the tiles
	bool getVisibility();//tells you if the animation is visible

	virtual void CalcBoundingRect( int& left, int& right, int& top, int& bottom );
	
protected:
	
	float stepTime;//tick time for moving through tiles
	float accumulator;//internal time keeper
	std::vector<SpriteBase*> tiles;	 //holds the individual tiles.
	
	int calculateRowIndex(int currenTile) const;
	int calculateColIndex(int ccurrentTile) const;
	int numTiles;
	int tilesWide;
	int tilesHigh;
	int currentTile;
	virtual void 	Render (const RenderWindow &Window) const ;
	bool isVisible;
};




#endif

Open in new window

ZoppoCommented:
Sorry, there's at least one error in the last part.

Replace 'std::vector<SpriteBase*>' with 'std::vector<Sprite*>'
ZoppoCommented:
Here is 'AnmiatedSprite.cpp'
#include "AnimatedSprite.h"
#include "Spritebase.h"


AnimatedSprite::AnimatedSprite() : SpriteBase()
{
}
		
AnimatedSprite::AnimatedSprite(const Image& Img, const Vector2f& Position, const Vector2f& Scale , float Rotation, const Color& Col ,int xTiles,int yTiles)
{
	tilesWide=xTiles;
	tilesHigh=yTiles;
	numTiles=xTiles*yTiles;
	currentTile=0;
	stepTime=1.0;
	for(int i=0;i<numTiles;i++)
	{	
	sf::Sprite* mySprite=new Sprite(Img,Position,Scale,Rotation);
	mySprite->SetSubRect(IntRect(calculateColIndex(i)*(Img.GetWidth()/xTiles),calculateRowIndex(i)*(Img.GetHeight()/yTiles),(calculateColIndex(i)+1)*(Img.GetWidth()/xTiles),(calculateRowIndex(i)+1)*(Img.GetHeight()/yTiles)));
	tiles.push_back(mySprite);
	}
	accumulator=0;
	isVisible=true;
	
}

AnimatedSprite::~AnimatedSprite()
{
	std::vector<Sprite*>::iterator it;
		for(it=tiles.begin();it!=tiles.end();++it)
		{
			delete *it;
			*it=0;
		}
}
void AnimatedSprite::update(float dt)
{
	if(isVisible)
	{
		accumulator+=dt;
		if(accumulator>stepTime) 
		{
			accumulator-=stepTime;
			currentTile=(currentTile+1)%numTiles;
		}
	}
}
void AnimatedSprite::Render (const RenderWindow &Window) const 
{
	if(isVisible)	Window.Draw(*tiles.at(currentTile));
}
	
int AnimatedSprite::calculateRowIndex(int cT) const
{
	return cT/tilesWide;
}

int AnimatedSprite::calculateColIndex(int cT) const
{
	return cT - tilesWide*calculateRowIndex(cT);
}

void AnimatedSprite::start()
{
	isVisible=true;
}
void AnimatedSprite::stop()
{
	isVisible=false;
}
void AnimatedSprite::setInterval(float stepTime)
{
	this->stepTime=stepTime;
}

bool AnimatedSprite::getVisibility()
{
	return isVisible;
}

virtual void AnimatedSprite::CalcBoundingRect( int& left, int& right, int& top, int& bottom )
{
 left = vector2f();
 top = vector2f();
 right = left + getWidth();
 bottom = top + getHeight();
}

Open in new window

ZoppoCommented:
Now 'ScrollSprite.h'
#ifndef SCROLL_SPRITE_H
#define SCROLL_SPRITE_H
#include <SFML/Graphics.hpp>
using namespace sf;

#include "SpriteBase.h"

class ScrollSprite : public SpriteBase
{
public:
	ScrollSprite();
	ScrollSprite(const Image &Img, const Vector2f &Position=Vector2f(1, 1), const Vector2f &Scale=Vector2f(1, 1), float Rotation=0.f, const Color &Col=Color(255, 255, 255, 255),float scrollPos=0.0);
	void setScrollPos(float scrollPos);
	void setVertPos(float vertPos);
	float getVertPos(void);
	float getScrollPos(void);

	virtual void CalcBoundingRect( int& left, int& right, int& top, int& bottom );
protected:
	float scrollPosition;//small d - the sprite is positioned in the scroll between 0 and D
	float verticalPosition;//the y co-ord 
	virtual void 	Render (const RenderWindow &Window) const ;
};




#endif

Open in new window

ZoppoCommented:
And finally 'ScrollSprite.cpp'
#include "ScrollSprite.h"

ScrollSprite::ScrollSprite():SpriteBase()
{
}

ScrollSprite::ScrollSprite(const Image &Img, const Vector2f &Position, const Vector2f &Scale, float Rotation, const Color &Col, float scrollPos):SpriteBase (Img, Position, Scale, Rotation, Col),scrollPosition(scrollPos)
{
}

void ScrollSprite::setScrollPos(float scrollPos)
{
	scrollPosition=scrollPos;
}
void ScrollSprite::setVertPos(float vertPos)
{
	verticalPosition=vertPos;
}

float ScrollSprite::getVertPos(void)
{
	return verticalPosition;
}

void ScrollSprite::Render (const RenderWindow &Window) const 
{
	Sprite::Render(Window);

}
float ScrollSprite::getScrollPos()
{
	return scrollPosition;
}

virtual void ScrollSprite::CalcBoundingRect( int& left, int& right, int& top, int& bottom )
{
 left = getScrollPos();
 top = getVertPos();
 right = left + getWidth();
 bottom = top + getHeight();
}

Open in new window

ZoppoCommented:
Maybe there still are compile bugs, but it shouldn't be as many as before, you could try to fix them yourself.

Unfortunateley I heave to leave for home now - see you tomorrow.

ZOPPO
tango2009Author Commented:
I have got the vast majority of the errors out. I had 84 at one point now I am down to just three that I cannot solve.

I have added coide for the length and width of the sprites for both animatedsprite and scrollsprite. However i get these three errors.

animatedsprite.cpp(84) : error C3861: 'vector2f': identifier not found
animatedsprite.cpp(85) : error C3861: 'vector2f': identifier not found
scrollsprite.cpp(8) : error C2614: 'ScrollSprite' : illegal member initialization: 'SpriteBase' is not a base or member
new-classes.zip
ZoppoCommented:
Well, the first two you'll have to solve yourself - I just copied this function from the code you posted in http:#30600191

About the second it's strange since if you used the code from http:#30633299 you'll see that in line 7 'ScrollSprite' is derived from 'SpriteBase' - please check if your code is similar ...
tango2009Author Commented:
Just one more question can I use this collsion detection function in an if statement in my main?

Something like this

If (DetectCollsion == true)
{


}
tango2009Author Commented:
Yes my code is derived from spritebase

It doesn't seem to like this part of the code

ScrollSprite::ScrollSprite(const Image &Img, const Vector2f &Position, const Vector2f &Scale, float Rotation, const Color &Col, float scrollPos):Spritebase (Img, Position, Scale, Rotation, Col),scrollPosition(scrollPos)

This is the error I get for this line of code

scrollsprite.cpp(8) : error C2661: 'Spritebase::Spritebase' : no overloaded function takes 5 arguments

any ideas?
ZoppoCommented:
You'll need to have to sprites to use it, i.e.

CScrollSprite sp;
AnimatedSprite ap;

if ( ap.DetectCollision( sp ) )
{
 // detected collision between sp and ap
 ...
}

So, in your case I guess you want to iterate through the list of sprites you have to find any collision - therefor you have to iterate through the list twice, i.e. like in the pseude-code

> SpriteBase sp1;
> for ( sp1 = <first sprite> to <last sprite> )
> {
>  SpriteBase sp2;
>  for ( sp2 = <next after sp1> to <last sprite> )
>  {
>   if ( sp1.DetectCollision( sp2 ) )
>   {
>    // handle collision between 'sp1' and 'sp2' here
>   }
>  }
> }

ZOPPO
ZoppoCommented:
ok, the other problem IMO comes from the fact I didn't implement that ctor to 'SpriteBase'.

Please add this in 'SpriteBase' declaration (header):

SpriteBase(const Image &Img, const Vector2f &Position=Vector2f(1, 1), const Vector2f &Scale=Vector2f(1, 1), float Rotation=0.f, const Color &Col=Color(255, 255, 255, 255),float scrollPos=0.0);

and this in 'SpriteBase' implementation (CPP):

SpriteBase::SpriteBase(const Image &Img, const Vector2f &Position=Vector2f(1, 1), const Vector2f &Scale=Vector2f(1, 1), float Rotation=0.f, const Color &Col=Color(255, 255, 255, 255),float scrollPos=0.0): Sprite( Img, Position, Scale, Rotation, Col, scrollPos ){}

ZOPPO
tango2009Author Commented:
I have added the code above but it seems to create more problems

With this line of code

Spritebase::Spritebase(const Image &Img, const Vector2f &Position=Vector2f(1, 1), const Vector2f &Scale=Vector2f(1, 1), float Rotation=0.f, const Color &Col=Color(255, 255, 255, 255),float scrollPos=0.0): Sprite( Img, Position, Scale, Rotation, Col)

I get these errors

spritebase.cpp(25) : error C2572: 'Spritebase::Spritebase' : redefinition of default parameter : parameter 2

spritebase.cpp(25) : error C2572: 'Spritebase::Spritebase' : redefinition of default parameter : parameter 3

I get four of these each refering to this line of code. Is this a problem that the names are the same as animatedsprite?

ZoppoCommented:
Sorry, mea culpa - just remove all expresions like '=Vector2f(1,1)' ...
tango2009Author Commented:
I have just one more error

Spritebase::Spritebase(const Image &Img, const Vector2f &Position, const Vector2f &Scale, float Rotation, const Color &Col, float scrollPos)
: Sprite( Img, Position, Scale, Rotation, Col, scrollPos )

spritebase.cpp(27) : error C2661: 'sf::Sprite::Sprite' : no overloaded function takes 6 arguments
tango2009Author Commented:
If I want to use position out of this code

AnimatedSprite::AnimatedSprite(const Image& Img, const Vector2f& Position, const Vector2f& Scale , float Rotation, const Color& Col ,int xTiles,int yTiles)

How do I create a pointer to this so I can use it in this code

 void AnimatedSprite::CalcBoundingRect( int& left, int& right, int& top, int& bottom )
{

 left = &Position();
 top = vector2f();
 right = left + getwidth();
 bottom = top + getlength();

}
ZoppoCommented:
Hi,

about the first: since I don't know the declaration of the 'Sprite' class I can only guess you may need to remove the 'scrollPos' from the base class constructor call, so instead of 'Sprite( Img, Position, Scale, Rotation, Col, scrollPos )' write 'Sprite( Img, Position, Scale, Rotation, Col )'

about the second one: I guess that 'Vector2f' is a struct/class which representates a 2D-vector. So, it should have methods to access the both values, maybe by direct accessing members (i.e. 'Vector2f::x') or by a function (i.e. 'Vector2f::GetX()').

Further I guess the 'Sprite' base class has a function to retrieve the position, i.e. 'GetPosition()'.

So, if these guesses are correct you should be able to write the function somehow like this:

void AnimatedSprite::CalcBoundingRect( int& left, int& right, int& top, int& bottom )
{
 left = GetPosition().GetX();
 top = GetPosition().GetY();
 right = left + getwidth();
 bottom = top + getlength();
}

ZOPPO
tango2009Author Commented:
I have sorted the first problem where as with the second problem I have ths header or hpp file for the 'Sprite'

Could either of these two be used?

 const IntRect& GetSubRect() const;

    ////////////////////////////////////////////////////////////
    /// Get the sprite size
    ///
    /// \return Size of the sprite
    ///
    ////////////////////////////////////////////////////////////
    Vector2f GetSize() const;

Would I have to implement them in the spritebase?
#ifndef SFML_SPRITE_HPP
#define SFML_SPRITE_HPP

////////////////////////////////////////////////////////////
// Headers
////////////////////////////////////////////////////////////
#include <SFML/Graphics/Drawable.hpp>
#include <SFML/Graphics/Rect.hpp>


namespace sf
{
class Image;

////////////////////////////////////////////////////////////
/// Sprite defines a sprite : texture, transformations,
/// color, and draw on screen
////////////////////////////////////////////////////////////
class SFML_API Sprite : public Drawable
{
public :

    ////////////////////////////////////////////////////////////
    /// Default constructor
    ///
    ////////////////////////////////////////////////////////////
    Sprite();

    ////////////////////////////////////////////////////////////
    /// Construct the sprite from a source image
    ///
    /// \param Img :      Image of the sprite
    /// \param Position : Position of the sprite (0, 0 by default)
    /// \param Scale :    Scale factor (1, 1 by default)
    /// \param Rotation : Orientation, in degrees (0 by default)
    /// \param Col :      Color of the sprite (white by default)
    ///
    ////////////////////////////////////////////////////////////
    Sprite(const Image& Img, const Vector2f& Position = Vector2f(0, 0), const Vector2f& Scale = Vector2f(1, 1), float Rotation = 0.f, const Color& Col = Color(255, 255, 255, 255));

    ////////////////////////////////////////////////////////////
    /// Change the image of the sprite
    ///
    /// \param Img : New image
    ///
    ////////////////////////////////////////////////////////////
    void SetImage(const Image& Img);

    ////////////////////////////////////////////////////////////
    /// Set the sub-rectangle of the sprite inside the source image.
    /// By default, the subrect covers the entire source image
    ///
    /// \param SubRect : New sub-rectangle
    ///
    ////////////////////////////////////////////////////////////
    void SetSubRect(const IntRect& SubRect);

    ////////////////////////////////////////////////////////////
    /// Resize the sprite (by changing its scale factors) (take 2 values).
    /// The default size is defined by the subrect
    ///
    /// \param Width :  New width (must be strictly positive)
    /// \param Height : New height (must be strictly positive)
    ///
    ////////////////////////////////////////////////////////////
    void Resize(float Width, float Height);

    ////////////////////////////////////////////////////////////
    /// Resize the sprite (by changing its scale factors) (take a 2D vector).
    /// The default size is defined by the subrect
    ///
    /// \param Size : New size (both coordinates must be strictly positive)
    ///
    ////////////////////////////////////////////////////////////
    void Resize(const Vector2f& Size);

    ////////////////////////////////////////////////////////////
    /// Flip the sprite horizontally
    ///
    /// \param Flipped : True to flip the sprite
    ///
    ////////////////////////////////////////////////////////////
    void FlipX(bool Flipped);

    ////////////////////////////////////////////////////////////
    /// Flip the sprite vertically
    ///
    /// \param Flipped : True to flip the sprite
    ///
    ////////////////////////////////////////////////////////////
    void FlipY(bool Flipped);

    ////////////////////////////////////////////////////////////
    /// Get the source image of the sprite
    ///
    /// \return Pointer to the image (can be NULL)
    ///
    ////////////////////////////////////////////////////////////
    const Image* GetImage() const;

    ////////////////////////////////////////////////////////////
    /// Get the sub-rectangle of the sprite inside the source image
    ///
    /// \return Sub-rectangle
    ///
    ////////////////////////////////////////////////////////////
    const IntRect& GetSubRect() const;

    ////////////////////////////////////////////////////////////
    /// Get the sprite size
    ///
    /// \return Size of the sprite
    ///
    ////////////////////////////////////////////////////////////
    Vector2f GetSize() const;

    ////////////////////////////////////////////////////////////
    /// Get the color of a given pixel in the sprite
    ///
    /// \param X : X coordinate of the pixel to get
    /// \param Y : Y coordinate of the pixel to get
    ///
    /// \return Color of pixel (X, Y)
    ///
    ////////////////////////////////////////////////////////////
    Color GetPixel(unsigned int X, unsigned int Y) const;

protected :

    ////////////////////////////////////////////////////////////
    /// /see Drawable::Render
    ///
    ////////////////////////////////////////////////////////////
    virtual void Render(const RenderWindow& Window) const;

private :

    ////////////////////////////////////////////////////////////
    // Member data
    ////////////////////////////////////////////////////////////
    const Image* myImage;      ///< Image used to draw the sprite
    IntRect      mySubRect;    ///< Sub-rectangle of source image to assign to the sprite
    bool         myIsFlippedX; ///< Is the sprite flipped on the X axis ?
    bool         myIsFlippedY; ///< Is the sprite flipped on the Y axis ?
};

} // namespace sf


#endif // SFML_SPRITE_HPP

Open in new window

ZoppoCommented:
Hm - hard to say - it might be the position isn't saved in 'Sprite' but in it's base class 'Drawable'. And I have no idea what 'GetSubRect()' is used for, but I would guess it can be used to tell a sprite to only render a given area of a larger image to allow using a large image for a number of sprites.

I guess these classes are from any third-party library - if so you should be able to find this out using the documentation of this library ... or by analyzing the headers ...
tango2009Author Commented:
Is there no way that I can just use position out of this code

AnimatedSprite::AnimatedSprite(const Image& Img, const Vector2f& Position, const Vector2f& Scale , float Rotation, const Color& Col ,int xTiles,int yTiles)

In my function below?

 void AnimatedSprite::CalcBoundingRect( int& left, int& right, int& top, int& bottom )
{

 left = Position();
 top = Position();
 right = left + getwidth();
 bottom = top + getlength();

}

Why is it that Position is undeclared when it is in AnimatedSprite.

One more hing you said earlier that you guess there would be functions for Vector2f getX but I dont have them in my classes and I just set tthem in an istance of animatedSprite if I am right like this

AnimatedSprite anim(aNimat,Vector2f(0,-50),Vector2f(9,1),0,Color(255,255,255,255),9,5);

tango2009Author Commented:
One more thing I have the drawable.hpp below is there a way I can use getPosition here in my collsion function?
class SFML_API Drawable
{
public :

    ////////////////////////////////////////////////////////////
    /// Default constructor
    ///
    /// \param Position : Position of the object (0, 0 by default)
    /// \param Scale :    Scale factor (1, 1 by default)
    /// \param Rotation : Orientation, in degrees (0 by default)
    /// \param Col :      Color of the object (white by default)
    ///
    ////////////////////////////////////////////////////////////
    Drawable(const Vector2f& Position = Vector2f(0, 0), const Vector2f& Scale = Vector2f(1, 1), float Rotation = 0.f, const Color& Col = Color(255, 255, 255, 255));

    ////////////////////////////////////////////////////////////
    /// Virtual destructor
    ///
    ////////////////////////////////////////////////////////////
    virtual ~Drawable();

    ////////////////////////////////////////////////////////////
    /// Set the position of the object (take 2 values)
    ///
    /// \param X : New X coordinate
    /// \param Y : New Y coordinate
    ///
    ////////////////////////////////////////////////////////////
    void SetPosition(float X, float Y);

    ////////////////////////////////////////////////////////////
    /// Set the position of the object (take a 2D vector)
    ///
    /// \param Position : New position
    ///
    ////////////////////////////////////////////////////////////
    void SetPosition(const Vector2f& Position);

    ////////////////////////////////////////////////////////////
    /// Set the X position of the object
    ///
    /// \param X : New X coordinate
    ///
    ////////////////////////////////////////////////////////////
    void SetX(float X);

    ////////////////////////////////////////////////////////////
    /// Set the Y position of the object
    ///
    /// \param Y : New Y coordinate
    ///
    ////////////////////////////////////////////////////////////
    void SetY(float Y);

    ////////////////////////////////////////////////////////////
    /// Set the scale of the object (take 2 values)
    ///
    /// \param ScaleX : New horizontal scale (must be strictly positive)
    /// \param ScaleY : New vertical scale (must be strictly positive)
    ///
    ////////////////////////////////////////////////////////////
    void SetScale(float ScaleX, float ScaleY);

    ////////////////////////////////////////////////////////////
    /// Set the scale of the object (take a 2D vector)
    ///
    /// \param Scale : New scale (both values must be strictly positive)
    ///
    ////////////////////////////////////////////////////////////
    void SetScale(const Vector2f& Scale);

    ////////////////////////////////////////////////////////////
    /// Set the X scale factor of the object
    ///
    /// \param X : New X scale factor
    ///
    ////////////////////////////////////////////////////////////
    void SetScaleX(float FactorX);

    ////////////////////////////////////////////////////////////
    /// Set the Y scale factor of the object
    ///
    /// \param Y : New Y scale factor
    ///
    ////////////////////////////////////////////////////////////
    void SetScaleY(float FactorY);

    ////////////////////////////////////////////////////////////
    /// Set the center of the object, in coordinates relative to the
    /// top-left of the object (take 2 values).
    /// The default center is (0, 0)
    ///
    /// \param CenterX : X coordinate of the center
    /// \param CenterY : Y coordinate of the center
    ///
    ////////////////////////////////////////////////////////////
    void SetCenter(float CenterX, float CenterY);

    ////////////////////////////////////////////////////////////
    /// Set the center of the object, in coordinates relative to the
    /// top-left of the object (take a 2D vector).
    /// The default center is (0, 0)
    ///
    /// \param Center : New center
    ///
    ////////////////////////////////////////////////////////////
    void SetCenter(const Vector2f& Center);

    ////////////////////////////////////////////////////////////
    /// Set the orientation of the object
    ///
    /// \param Rotation : Angle of rotation, in degrees
    ///
    ////////////////////////////////////////////////////////////
    void SetRotation(float Rotation);

    ////////////////////////////////////////////////////////////
    /// Set the color of the object.
    /// The default color is white
    ///
    /// \param Col : New color
    ///
    ////////////////////////////////////////////////////////////
    void SetColor(const Color& Col);

    ////////////////////////////////////////////////////////////
    /// Set the blending mode for the object.
    /// The default blend mode is Blend::Alpha
    ///
    /// \param Mode : New blending mode
    ///
    ////////////////////////////////////////////////////////////
    void SetBlendMode(Blend::Mode Mode);

    ////////////////////////////////////////////////////////////
    /// Get the position of the object
    ///
    /// \return Current position
    ///
    ////////////////////////////////////////////////////////////
    const Vector2f& GetPosition() const;

    ////////////////////////////////////////////////////////////
    /// Get the current scale of the object
    ///
    /// \return Current scale factor (always positive)
    ///
    ////////////////////////////////////////////////////////////
    const Vector2f& GetScale() const;

    ////////////////////////////////////////////////////////////
    /// Get the center of the object
    ///
    /// \return Current position of the center
    ///
    ////////////////////////////////////////////////////////////
    const Vector2f& GetCenter() const;

    ////////////////////////////////////////////////////////////
    /// Get the orientation of the object.
    /// Rotation is always in the range [0, 360]
    ///
    /// \return Current rotation, in degrees
    ///
    ////////////////////////////////////////////////////////////
    float GetRotation() const;

    ////////////////////////////////////////////////////////////
    /// Get the color of the object
    ///
    /// \return Current color
    ///
    ////////////////////////////////////////////////////////////
    const Color& GetColor() const;

    ////////////////////////////////////////////////////////////
    /// Get the current blending mode
    ///
    /// \return Current blending mode
    ///
    ////////////////////////////////////////////////////////////
    Blend::Mode GetBlendMode() const;

    ////////////////////////////////////////////////////////////
    /// Move the object of a given offset (take 2 values)
    ///
    /// \param OffsetX : X offset
    /// \param OffsetY : Y offset
    ///
    ////////////////////////////////////////////////////////////
    void Move(float OffsetX, float OffsetY);

    ////////////////////////////////////////////////////////////
    /// Move the object of a given offset (take a 2D vector)
    ///
    /// \param Offset : Amount of units to move the object of
    ///
    ////////////////////////////////////////////////////////////
    void Move(const Vector2f& Offset);

    ////////////////////////////////////////////////////////////
    /// Scale the object (take 2 values)
    ///
    /// \param FactorX : Scaling factor on X (must be strictly positive)
    /// \param FactorY : Scaling factor on Y (must be strictly positive)
    ///
    ////////////////////////////////////////////////////////////
    void Scale(float FactorX, float FactorY);

    ////////////////////////////////////////////////////////////
    /// Scale the object (take a 2D vector)
    ///
    /// \param Factor : Scaling factors (both values must be strictly positive)
    ///
    ////////////////////////////////////////////////////////////
    void Scale(const Vector2f& Factor);

    ////////////////////////////////////////////////////////////
    /// Rotate the object
    ///
    /// \param Angle : Angle of rotation, in degrees
    ///
    ////////////////////////////////////////////////////////////
    void Rotate(float Angle);

protected :

    ////////////////////////////////////////////////////////////
    /// Get the transform matrix of the drawable
    ///
    /// \return Transform matrix
    ///
    ////////////////////////////////////////////////////////////
    const Matrix3& GetMatrix() const;

private :

    friend class RenderWindow;

    ////////////////////////////////////////////////////////////
    /// Draw the object into the specified window
    ///
    /// \param Window : Window into which draw the object
    ///
    ////////////////////////////////////////////////////////////
    void Draw(const RenderWindow& Window) const;

    ////////////////////////////////////////////////////////////
    /// Render the specific geometry of the object
    ///
    /// \param Window : Window into which render the object
    ///
    ////////////////////////////////////////////////////////////
    virtual void Render(const RenderWindow& Window) const = 0;

    ////////////////////////////////////////////////////////////
    // Member data
    ////////////////////////////////////////////////////////////
    Vector2f        myPosition;   ///< Position of the object on screen
    Vector2f        myScale;      ///< Scale of the object
    Vector2f        myCenter;     ///< Origin of translation / rotation / scaling of the object
    float           myRotation;   ///< Orientation of the object, in degrees
    Color           myColor;      ///< Overlay color of the object
    Blend::Mode     myBlendMode;  ///< Blending mode
    mutable bool    myNeedUpdate; ///< Do we need to recompute the transform matrix ?
    mutable Matrix3 myMatrix;     ///< Precomputed transform matrix gathering the translation / rotation / scale / center
};

} // namespace sf


#endif // SFML_DRAWABLE_HPP

Open in new window

ZoppoCommented:
>> Is there no way that I can just use position out of this code

No - 'Position' is just a parameter passed to the constructor of 'AnimatedSprite' which IMO then is passed to the base class.

>> Why is it that Position is undeclared when it is in AnimatedSprite.

As you can see from the headers 'Position' is neither member of 'AnimatedSprite' nor 'Sprite' allthough it's passed to the constructor, so I guess it is passed to base class constructor.

But, as you told, from the 'drawable.hpp' there's a function 'Drawable::GetPosition', this is what you need. So my last posted function goes to the right direction, I just guess the 'Vector2f' doesn't have a 'GetX' and 'GetY' function - take a look at how it is declared and replace these function calls with the appropriate ones.

tango2009Author Commented:
So I should use this function

const Vector2f& GetPosition() const;

I have changed the left variable to a float and I am trying to call this function like this

left = Drawable::GetPosition();

this however will not convert a float into a vector. Does this mean that I have to change the way I am declaring the variable?
ZoppoCommented:
That's clear - a 'Vector2f' is a struct/class which representates 2 values, one for X and one for Y - you cannot assign such a struct/class to a single numeric value like a 'float'.

So, as told, the 'Vector2f' must have a possibility to find the X- and Y-coordinates. With this you need to set 'left' to the X- and 'top to the Y-coordinate of the 'Vector2f' returned by 'GetPosition'.

It's most probably something like
> left = Drawable::GetPosition().x;
or
> left = Drawable::GetPosition().GetX();
or
> left = Drawable::GetPosition().get_x();
or
> left = Drawable::GetPosition().X();
or anything else - check the header where 'Vector2f' is declared to find the correct one ...
tango2009Author Commented:
ok thats fine. Just going back to the width and length in my previous function. At the moment I am trying to use them like this

 void AnimatedSprite::CalcBoundingRect( int& left, int& right, int& top, int& bottom )
{

      left = Drawable::GetPosition().x;

      right = Drawable::GetPosition().y;
 
      top = Drawable::GetScale().x;


      bottom = Drawable::GetScale().y;

}

Where GetScale is declared like this

const Vector2f& GetScale() const;

void SetScale(float ScaleX, float ScaleY);

    ////////////////////////////////////////////////////////////
    /// Set the scale of the object (take a 2D vector)
    ///
    /// \param Scale : New scale (both values must be strictly positive)
    ///
    ////////////////////////////////////////////////////////////

Would this work better than width and height?
tango2009Author Commented:
About your comment earlier when it comes to the main I have this code so far


if ( ap.DetectCollision( sp ) )
{
 // detected collision between sp and ap
 ...
}

Do I need to have one of these for each scrollingsprite. I know you said it would be best to iterate through the sprites but I only want to check collisions between animatedsprite and the different scrollingsprites.
ZoppoCommented:
ok, first I don't know exactly what the scale is used for, but I could imagine you need both the scale and the height/width - i.e. if the height/width is the size of the sprite in pixels and the scale is a scaling factor, then you'll have to calculate i.e. the bounding box width by 'GetWidth() * GetScale().x' - maybe you need to cast the width to float before to avoid rounding errors, i.e.:

> int width = (int)( (float)GetWidth() * GetScale().x );

Further you forgot in the last code to add the top/left to bottom/right, it should be something like:

> right = left + ...;
> bottom = top + ...;

About the last: Well, you simply have to know which sprites you want to check for collision - if you have a list of 'ScrollSprites' and one or more 'AnimatedSprite's you'll have to call per 'AnimatedSprite' the 'DetectCollision' for all 'ScrollSprites', i.e. like in this pseudo code:

> for ( ap = <first AnimatedSprite> to <last AnimatedSprite> )
> {
>  for ( sp = <first ScrollSprite> to <last ScrollSprite> )
>  {
>   if ( ap.DetectCollision( sp ) )
>   {
>    // handle collision here ...
>   }
>  }
> }

BTW, just a hint: Within a class-function implementation you don't need to use base-classes namespace - so you can i.e. write 'left = GetPosition().x' instead of 'left = Drawable::GetPosition().x' in your code above.

ZOPPO
tango2009Author Commented:
If I have an int width like the one you suggested

int width = (int)( (float)GetWidth() * GetScale().x );

do I need to pass this int into animatedsprite or can I just declare it in the header.

tango2009Author Commented:
With the for loop do I need something like this, am I on the right track here

for (sp = ScrollSprite > ScrollSprite10 sp++)
       {
       }
ZoppoCommented:
> do I need to pass this int into animatedsprite or can I just declare it in the header.

None of these - you should use it in 'CalcBoundingRect' to calculate the right/bottom like:

> right = left + width;

How your loop looks depends on how you store the sprites. If you i.e. have a 'std::vector< SpriteBase* > scrollSprites' and one 'AnimatedSprite as;' you can do:

> for ( std::vector< SpriteBase* >::iterator it = scrollSprites.begin(); it != scrollSprites.end(); it++ )
> {
>  if ( (*it)->as.DetectCollision( as ) )
>  { ... }
> }

ZOPPO


PS: I don't want to anyhow blame on you but I think it might be a good idea if you could take some time to learn some more C++ basics - about 80% of your questions in this thread are quite trivial C++ and it's difficult for both of us to get your stuff working this way.
tango2009Author Commented:
Yes sorry I normally do c# and mainly java so sorry if my questions seem a bit dumb. I just have problems with some of the syntax. I only have two more small problems with my code.

First I have two errors with this code

for ( std::vector< ScrollSprite* >::iterator it = pSprite.begin(); it != pSprite.end(); it++ )
                {
                if ( (*it)->ap.DetectCollision( ap ) )
                        {
                        }
                }

I get these two errors

error C2039: 'ap' : is not a member of 'ScrollSprite'

I have added this code in the main aswell

ScrollSprite ap;

The second error is this

mainscroller.cpp(273) : error C2228: left of '.DetectCollision' must have class/struct/union
ZoppoCommented:
Sorry, my mistake - unfortunately those typos happen since I cannot compile anything for test purpose.

To solve this error simply remove the 'ap.' befor 'DetectCollision'.

ZOPPO
tango2009Author Commented:
The only other problem I have is with this code

void AnimatedSprite::CalcBoundingRect( int& left, int& right, int& top, int& bottom )
{

      left = Drawable::GetPosition().x;

      int width = (int)( (float)getWidth() * GetScale().x );

      right = left + Drawable::GetScale().y;
 
      top = Drawable::GetPosition().y;

      bottom = top + Drawable::GetScale().x;

}

I think I need to access this code in Sprite.hpp

void Resize(float Width, float Height);

would it be better to change the code to somehting like this

int width = (int)( (float)Sprite::Resize() * GetScale().x );
ZoppoCommented:
I don't know, but I guess the 'Resize' function is used to modify the scale of the sprite (which you recieve with 'GetScale'), so I don't think you should use it here since you don't want to change the sprite in this function.

I'm not really sure how you can detect width/height of the sprite, maybe you though could use the 'GetSubRect' function.

Unfortunateley I even don't know what functions/members the class 'IntRect' has. So, for now I assume this class has a function 'Width()' to determine its width and 'Height()' to determine its height. If they are named different please change it.

With this assumption you could write the function like this:

void AnimatedSprite::CalcBoundingRect( int& left, int& right, int& top, int& bottom )
{
      left = GetPosition().x;
      right = left + (int)( (float)GetSubRect().Width() * GetScale().x );
 
      top = GetPosition().y;
      bottom = top + (int)( (float)GetSubRect().Height() * GetScale().y );
}

ZOPPO
tango2009Author Commented:
Yes I do have functions to determine getWidth and getHeight

I have changed my function to this

 void AnimatedSprite::CalcBoundingRect( int& left, int& right, int& top, int& bottom )
{

      left = Drawable::GetPosition().x;

      right = left + (int)( (float)GetSubRect().GetWidth * GetScale().x );
 
      top = Drawable::GetPosition().y;

      bottom = top + (int)( (float)GetSubRect().GetHeight * GetScale().y );

}

I get these errors

animatedsprite.cpp(86) : error C2440: 'type cast' : cannot convert from 'overloaded-function' to 'float'

is there anyway around this conversion problem?
ZoppoCommented:
You forgot the '()' after 'GetWidth' and 'GetHeight', so it has to be like this:

void AnimatedSprite::CalcBoundingRect( int& left, int& right, int& top, int& bottom )
{

      left = Drawable::GetPosition().x;

      right = left + (int)( (float)GetSubRect().GetWidth() * GetScale().x );
 
      top = Drawable::GetPosition().y;

      bottom = top + (int)( (float)GetSubRect().GetHeight() * GetScale().y );

}
ZoppoCommented:
BTW, I suggest again that you leave out the 'Drawable::' within this code - i.e. it might be that somewhen in future you like to override the 'GetPosition()' function for 'AnimatedSprite' - if so your code then would still call 'Drawable::GetPosition()' instead of 'AnimatedSprite::GetPosition()'.

And of course you save time with typing :o)

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
tango2009Author Commented:
Thankyou for your help I would give you more points if I could
tango2009Author Commented:
Sorry to open this up again  I just have a problem with my collisions. At the moment I am trying to check collisions between anim sprite and all of the scrolling sprites and I am using the code from earlier that I have changed.

      for ( std::vector< ScrollSprite* >::iterator it = pSprite.begin(); it != pSprite.end(); it++ )
                {
                if ( (*it)->DetectCollision( anim ) )
                        {
                           
                              App.Draw(explo);
                    PlaySound(L"sounds/explosion1.wav",NULL,SND_FILENAME|SND_LOOP|SND_SYNC);
                    //anim.SetPosition(50,50);
                              lives -= 1;
                        }
                }

Below is my vector of sprites. Is there a problem with how I have set up the iterator?
std::vector<ScrollSprite*> pSprite;
	pSprite.push_back(&scrollingSprite);
	pSprite.push_back(&scrollingSprite1);
	pSprite.push_back(&scrollingSprite2);
	pSprite.push_back(&scrollingSprite3);
	pSprite.push_back(&scrollingSprite4);
	pSprite.push_back(&scrollingSprite5);
	pSprite.push_back(&scrollingSprite6);
	pSprite.push_back(&scrollingSprite7);
	pSprite.push_back(&scrollingSprite8);
	pSprite.push_back(&scrollingSprite9);
	pSprite.push_back(&scrollingSprite10);

Open in new window

tango2009Author Commented:
Sorry I didnt tell you what is going wrong. This function only seems to be checking collisions with the first two or three sprites in the scroller vector.
ZoppoCommented:
> This function only seems to be checking collisions with the first two or three sprites in the scroller vector.

The loop IMO looks ok and should test all sprites from 'pSprite' against 'anim'.

Could you verify that it is really not called for all by inserting some tracing output to 'DetectCollection'? Best would be to log the both calculated bounding boxes too since it may be the bounding boxes are somehow calculated wrong.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Game Programming

From novice to tech pro — start learning today.