@Daslee: that seems to be specific to your project - he may have entirely different requirements for control, which is why I asked for more info.
@Fred50: Simply put, things are not that simplistic. It's not just "gravity and boundaries" - we have to program the details of how everything functions, and the way these things work is part of the game as a whole. A top-down game will have different mechanics than a platformer, RTS, or RPG, for example.
If you want something robust enough for a game, you need to put together a simple "pseudo-physics" framework that allows you to abstract the collision logic. This really isn't that hard, but it requires a general understanding of what exactly you want to accomplish and how you want to go about doing that. I'll offer an example setup that should work for a simple 2D platformer; you could easily make a similar setup for a 3D project.
Okay, so you will have a two different components in this system:Body:
A simple "body" that represents a physical object (e.g., the player). It needs a collision identifier (most likely a bounding box), a location, and things like velocity, mass, acceleration.Surface:
A traversable section of the world. It also needs a collision identifier (either a bounding box or a line segment, either works well).
Maintain a list of all Bodies and all Surfaces. Now, each time you update the game, you do several things:
- Accelerate all Bodies in the direction of gravity (probably -Y) at the rate of gravitic acceleration.
- Compare all Bodies to all Surfaces that they collide with. For each body, build a list of the surfaces it is in contact with.
- Have each Body resolve its collisions (stop falling/slide/bounce/whatever) with the Surfaces in its list.
Now, we've got the basics of our "physics" system going. The nice thing about this is that we can easily extend it and add more functionality. For example, we could give Bodies and Surfaces friction. We could have surface normals on our Surface objects, allowing Bodies to slide downhill.
The most useful thing, however, is that we have an easy way to tie player input with the environment. Since we build a list of the Surfaces the player is standing on every frame, we can factor that into player controls. Example: the player can only jump if he is standing on a surface.
You see how this works? By making your setup more abstract and more of a "system," it's easier to do cool things with it.
NOTE: You mentioned that you wanted to stop the player from moving offscreen. This is not
a collision issue, this is a camera issue. It's a different problem with a different solution, and is connected to your rendering more than anything else.