Unreal Engine 2D: Staying In Map Limits

So in this lesson, we are writing two functions two check boundaries, and doing two separate calls to check the X and Z axis.

Would there be an issue creating a single function taking in both Vector2D variables and then checking all four values? I would assume if one of those turned out to be false (or multiple), you would just either subtract the DistanceToMove vector, or set NewLocation as Current Location, right?

Or would that mess something up? It just seems like a lot of extra functions and calls when it could be consolidated.

Hi Robert,
There’s no reason why you can’t do that. Saying that, I created a really nice solution to this problem and for the life of me I can’t find the code any more. I was going to share it with you here.

It was something along the lines of:

    auto const ActorPosition{GetActorLocation()};
    auto const X{FMath::Clamp(ActorPosition.X + Movement.X, BottomLeftLimit.X, TopRightLimit.X)};
    auto const Z{FMath::Clamp(ActorPosition.Z + Movement.Y, BottomLeftLimit.Y, TopRightLimit.Y)};

Where 2 vectors defined the top-left and bottom-right of the bounds rather than the x bounds and y bounds and the Movement is the input Normalized. Then you just set the new player X and Z accordingly. The big advantage of this is that the player can still move along the edges and doesn’t stop when a bound is hit, unless it is a corner of course.

Hope this helps in your thinking

1 Like

I think combining both checks into one function could definitely streamline things. As long as you handle both axes properly in the same function, it shouldn’t cause problems. If one of the checks fails, you could adjust the movement vector or just keep the current location, which would save you the hassle of having multiple functions for each axis. I’ve done similar things before when I wanted to keep code simple but still handle edge cases, and as long as the logic is clear, it should work fine.

1 Like

Privacy & Terms