Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Implementing "place_empty" function in C++ from GameMaker  (Read 2159 times)

0 Members and 1 Guest are viewing this topic.

fancode992

  • Newbie
  • *
  • Posts: 3
    • View Profile
Implementing "place_empty" function in C++ from GameMaker
« on: May 16, 2021, 11:53:35 am »
Hi, recently I started writing a 2D game in C++ with SFML but now I'm stuck in the collision mechanism. I want to program the entities in a way so that every time Update() is called I check whether they are touching with solid objects and determine how they should move (up/down left/right).

In case you didn't know, in GameMaker (legacy versions) there are two functions, place_empty(x, y) which checks if there is a collision box in the given coordinates and position_empty(x, y) which checks if the calling object interacts with another object in the given coordinates.

bool PositionFree(sf::Vector2f Position, bool Solid) {
    // GetEntities() returns a pointer to this type -> std::vector<CEntity*>
    for (auto Entity : GetEntities()) {
        //printf("EntPosX = %.1f, EntSizeX = %.1f, PosX = %.1f\n", Entity->GetPosition().x, Entity->GetSize().x, Position.x);
        //printf("EntPosY = %.1f, EntSizeY = %.1f, PosY = %.1f\n\n", Entity->GetPosition().y, Entity->GetSize().y, Position.y);
       
        if (Entity->IsSolid() != Solid) {
            continue;
        }
       
        if (Position.y > Entity->GetPosition().y && Position.y < Entity->GetPosition().y + Entity->GetSize().y) {
            if (Position.x < Entity->GetPosition().x) {
                return true;
            }
        }
    }
    return true;
}

I have this utility function but it doesn't work as expected. The vertical Y position works fine (I guess?) but the horizontal X line does not. Can you help me rewrite it correctly? :)

- regards, fancode992

kojack

  • Sr. Member
  • ****
  • Posts: 343
  • C++/C# game dev teacher.
    • View Profile
Re: Implementing "place_empty" function in C++ from GameMaker
« Reply #1 on: May 16, 2021, 01:14:13 pm »
The Y part looks right, it's checking if the test point is below the top of the entity and above the bottom (so within the vertical range of the entity).
The X part is only checking if the test point is to the left of the entity.

Changing the X code to match the Y code should fix it.
if (Position.y > Entity->GetPosition().y && Position.y < Entity->GetPosition().y + Entity->GetSize().y) {
            if (Position.x > Entity->GetPosition().x && Position.x < Entity->GetPosition().x + Entity->GetSize().x) {
                return true;
            }
        }
The bottom return true should probably be return false though, since it fell through there because no entity overlapped the test point.