C++ C++ SDL2 tile map collision platformer

Recommended Posts

I'm trying to do platformer with a map reading from a file. I did it. It works well. The problem with it is, I don't know how to implement collision for it, that would be more advanced. I would like to add some more things like moving platforms etc. in the future. I wrote this : File Manager :

void FileManager::LoadFromFile(std::string fileName, 
std::vector<std::vector<int>> &map, std::vector<std::vector<int>> &col, 
std::vector<std::vector<int>> &shadow)
{
fileName = "Files/Config/" + fileName;
std::ifstream openFile(fileName);

map.clear();
col.clear();

if (openFile.is_open())
{
    while (!openFile.eof())
    {
        std::string line;
        std::getline(openFile, line);

        std::vector<int> tempVector;

        if (line.find("[map]") != std::string::npos)
        {
            tempVector.clear();
            state = MAP;
            continue;
        }
        else if(line.find("[collision]") != std::string::npos)
        {
            tempVector.clear();
            state = COLLISION;
            continue;
        }
        else if (line.find("[shadows]") != std::string::npos)
        {
            tempVector.clear();
            state = SHADOW;
            continue;
        }
        std::stringstream str(line);

        while (str)
        {
            std::getline(str, line, ' ');

            if (line != "")
            {
                switch (state)
                {
                    case MAP: tempVector.push_back(atoi(line.c_str())); break;
                    case COLLISION: tempVector.push_back(atoi(line.c_str())); break;
                    case SHADOW: tempVector.push_back(atoi(line.c_str())); break;
                }
            }
        }

        switch (state)
        {
            if (tempVector.size() > 0)
            {
                case MAP: map.push_back(tempVector); break;
                case COLLISION: col.push_back(tempVector); break;
                case SHADOW: shadow.push_back(tempVector); break;
            }

            tempVector.clear();
        }   
    }
}

openFile.clear();
openFile.close();
}

it reads from a file a tile map and a collision map

 

//----------------------------------------------

//------------- GameplayScreen -----------------

bool GameplayScreen::checkCollision(int pLeft, int pTop, int pRight, int 
pBot)
{
   for (int y = 0; y < col.size(); y++)
   {
       for (int x = 0;x < col[y].size(); x++)
       {
           if (col[y][x] != 0)
           {
               int top = y * 32;
               int bot = y * 32 + 32;
               int left = x * 32;
               int right = x * 32 + 32;

               if (pRight < left || pLeft > right || pTop > bot || pBot < top)
               {
                   std::cout << "NIC" << std::endl;
                   return false;
               }
               else
               {
                   std::cout << "COLLISION" << std::endl;
                   return true;
               }
           }
       }
   }
}

this method is going through the collision map, and if somewhere in a file is a number 1, it means that this block is collideable. If it's 0 it means this block isn't colideable. So if somewhere is 1 it returns collision.

//----------------------------------------------

//-------------- Player engine -----------------

https://pastebin.com/P4kCNxNs

Config::getSM() stands for ScreenManager that handle all screens like main menu, options menu, gameplay screen etc. ->GetGame() returns GameplayScreen instance which handle player class, enemies, tiles. ->getPosX() returns position of a map, because it's moving depends of player direction and position. If movespeed is negative, player is moving left, if positive, player moving right. If checkCollision returns false that mean, there is no collision, so player can easly move left or right. So I did check, if(!Config::getSM()->GetGame()->checkCollision()). The problem is that, it always returns false. How can I make it works? How can I make my code more advance?

Share this post


Link to post
Share on other sites

One of the grand "features" of a tile map is that you can calculate the overlapped tiles from a rectangle easily. So you don't have to traverse the full map:

int x1 = pLeft / 32;
int x2 = ( pRight + 31 ) / 32;
int y1 = pTop / 32;
int y2 = ( pBottom + 31 ) / 32;

for ( int y = y1; y <= y2; ++y )
{  
  for ( in x = x1; x <= x2; ++x )  
  {    
    if ( col[y][x] != 0 )    
    {      
      // collision!    
    }  
  }
}

 

PS: why the P prefix?

 

PSS: This code message editor is annoying me to no end! Why the hell does it remove all line breaks whenever I go to code view.

Share this post


Link to post
Share on other sites

P stands for player. Did I forget to say? I'll try this code out soon. Thank you for the answer. I'm wondering about, I don't know how to name this method, collision like this :
left top, right top
left bottom, right bottom
left center, right center
Divide the blocks into these pieces and then compare with player. Have you got any "grand <eatures" for this? 

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now


  • Forum Statistics

    • Total Topics
      628722
    • Total Posts
      2984397
  • Similar Content

    • By Josheir
      void update() { if (thrust) { dx += cos(angle*DEGTORAD)*.02; dy += sin(angle*DEGTORAD)*.02; } else { dx*=0.99; dy*=0.99; } int maxSpeed = 15; float speed = sqrt(dx*dx+dy*dy); if (speed>maxSpeed) { dx *= maxSpeed/speed; dy *= maxSpeed/speed; } x+=dx; y+=dy; . . . } In the above code, why is maxSpeed being divided by the speed variable.  I'm stumped.
       
      Thank you,
      Josheir
    • By Benjamin Shefte
      Hey there,  I have this old code im trying to compile using GCC and am running into a few issues..
      im trying to figure out how to convert these functions to gcc
      static __int64 MyQueryPerformanceFrequency() { static __int64 aFreq = 0; if(aFreq!=0) return aFreq; LARGE_INTEGER s1, e1, f1; __int64 s2, e2, f2; QueryPerformanceCounter(&s1); s2 = MyQueryPerformanceCounter(); Sleep(50); e2 = MyQueryPerformanceCounter(); QueryPerformanceCounter(&e1); QueryPerformanceFrequency(&f1); double aTime = (double)(e1.QuadPart - s1.QuadPart)/f1.QuadPart; f2 = (e2 - s2)/aTime; aFreq = f2; return aFreq; } void PerfTimer::GlobalStart(const char *theName) { gPerfTimerStarted = true; gPerfTotalTime = 0; gPerfTimerStartCount = 0; gPerfElapsedTime = 0; LARGE_INTEGER anInt; QueryPerformanceCounter(&anInt); gPerfResetTick = anInt.QuadPart; } /////////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////////////// void PerfTimer::GlobalStop(const char *theName) { LARGE_INTEGER anInt; QueryPerformanceCounter(&anInt); LARGE_INTEGER aFreq; QueryPerformanceFrequency(&aFreq); gPerfElapsedTime = (double)(anInt.QuadPart - gPerfResetTick)/aFreq.QuadPart*1000.0; gPerfTimerStarted = false; }  
      I also tried converting this function (original function is the first function below and my converted for gcc function is under that) is this correct?:
      #if defined(WIN32) static __int64 MyQueryPerformanceCounter() { // LARGE_INTEGER anInt; // QueryPerformanceCounter(&anInt); // return anInt.QuadPart; #if defined(WIN32) unsigned long x,y; _asm { rdtsc mov x, eax mov y, edx } __int64 result = y; result<<=32; result|=x; return result; } #else static __int64 MyQueryPerformanceCounter() { struct timeval t1, t2; double elapsedTime; // start timer gettimeofday(&t1, NULL); Sleep(50); // stop timer gettimeofday(&t2, NULL); // compute and print the elapsed time in millisec elapsedTime = (t2.tv_sec - t1.tv_sec) * 1000.0; // sec to ms elapsedTime += (t2.tv_usec - t1.tv_usec) / 1000.0; // us to ms return elapsedTime; } #endif Any help would be appreciated, Thank you!
    • By mister345
      Hi, I'm building a game engine using DirectX11 in c++.
      I need a basic physics engine to handle collisions and motion, and no time to write my own.
      What is the easiest solution for this? Bullet and PhysX both seem too complicated and would still require writing my own wrapper classes, it seems. 
      I found this thing called PAL - physics abstraction layer that can support bullet, physx, etc, but it's so old and no info on how to download or install it.
      The simpler the better. Please let me know, thanks!
    • By lawnjelly
      It comes that time again when I try and get my PC build working on Android via Android Studio. All was going swimmingly, it ran in the emulator fine, but on my first actual test device (Google Nexus 7 2012 tablet (32 bit ARM Cortex-A9, ARM v7A architecture)) I was getting a 'SIGBUS illegal alignment' crash.
      My little research has indicated that while x86 is fine with loading 16 / 32 / 64 bit values from any byte address in memory, the earlier ARM chips may need data to be aligned to the data size. This isn't a massive problem, and I see the reason for it (probably faster, like SIMD aligned loads, and simpler for the CPU). I probably have quite a few of these, particular in my own byte packed file formats. I can adjust the exporter / formats so that they are using the required alignment.
      Just to confirm, if anyone knows this, is it all 16 / 32 / 64 bit accesses that need to be data size aligned on early android devices? Or e.g. just 64 bit size access? 
      And is there any easy way to get the compiler to spit out some kind of useful information as to the alignment of each member of a struct / class, so I can quickly pin down the culprits?
      The ARM docs (http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.faqs/ka15414.html) suggest another alternative is using a __packed qualifier. Anyone used this, is this practical?
    • By Josheir
      In the following code:

       
      Point p = a[1]; center of rotation for (int i = 0; I<4; i++) { int x = a[i].x - p.x; int y = a[i].y - p.y; a[i].x = y + p.x; a[i].y = - x + p.y; }  
      I am understanding that a 90 degree shift results in a change like:   
      xNew = -y
      yNew = x
       
      Could someone please explain how the two additions and subtractions of the p.x and p.y works?
       
      Thank you,
      Josheir
  • Popular Now