• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0

How do I implement some physics in my 2D game?

2 posts in this topic

I have a 2D Side-scroller game written in C using SDL. I chose C because at the time I was most comfortable with it, plus I don't really know C++, so there you have it smile.png


This is how my game looks like at the moment.





You can probably immediately notice(or not tongue.png ) that I was inspired by Mario. I don't plan to make a clone, so I am thinking of stuff as I go. But right now, my physics are not properly or at all implemented. I did make jumping and falling work, but they don't work as you might expect them to.

My jumping for now is basically moving the player a few pixels above, no force, no acceleration or deceleration. My "gravity" is basically checking whether there is a solid tile below the player(and the tile next to it which I will explain why further down) and if not, I fall. But again, no deceleration there.


Here is how my jumping and "gravity" code which I will try to explain why I've done it the way I have.

    if(player.key_press[SDLK_SPACE] && !player.is_jumping)


        player.is_jumping = true;

        player.pos.y -= 5000 * delta;

        if(player.pos.y < 0.0)


            player.pos.y = 0.0;




    int tile_below = get_tile_below_player();

    int next_tile_below = tile_below + 1;

    int player_row = get_player_row();

    int player_col = get_player_col();

    bool fall = false;

    bool can_check_below = true;

    int distance;


    if((get_tiles_per_row(player_row) - 1) == player_col)

        can_check_below = false;


    if((Map->tile[tile_below].type != ENUM_TILE_AIR || (can_check_below && Map->tile[next_tile_below].type != ENUM_TILE_AIR)) && (distance = collision_distance_rect(player.pos, Map->tile[next_tile_below])) != 0)


        player.pos.y -= distance;



    if(Map->tile[tile_below].type == ENUM_TILE_AIR)


        fall = true;


        if(can_check_below && (Map->tile[next_tile_below].type != ENUM_TILE_AIR) && check_collision_below(player.pos, Map->tile[next_tile_below]))


            fall = false;



    if((Map->tile[tile_below].type == ENUM_TILE_DIRT || (can_check_below && Map->tile[next_tile_below].type == ENUM_TILE_DIRT)) && player.is_jumping)


        player.is_jumping = false;





        player.pos.y += 300 * delta; // no collision detection, I clip. Will fix. Fix implemented above.


The first bit is my if statement where I check if the space bar was pressed and the player is not in a jumping state, and then "jump" which you see is 5000 * delta, where delta is a constant basically, part of my implementation of a fixed timestep, which I have not yet properly implemented, but I will get around to doing that.


After that is the code where all my magic happens tongue.png. But first let me explain why I need to check not only the tile below the player, but the tile next to it.

You see I store my map in an array of structures, not a 2D array. The problem with this method is that you can't know immediately which tile you are on, so after many many days of thinking I was finally hinted at how to calculate the index for my map.


So here, I treat my map as rows and columns. To calculate which row a player is on, I do the following arithmetic

player.pos.y / TILE_HEIGHT

I divide the player's position by the tile's height. To get the column I am in, I do

player.pos.x / TILE_WIDTH

And I calculate the index of the of the tile in my struct array like so index = (player_row * tiles_per_row) + player_col. However although it works, it produces some edge-case bugs which I can only describe with pictures


Now, in that picture I've numbered the columns, where do you think my player is(the red square)? The correct answer is, column 2, if you look closely one pixel is still in column 2. Why is it in column 2? Let's do some math. If we assume that my tiles are 32x32, and that my player's position on the X coordinate is 95, then using the formula player.pos.x / TILE_WIDTH would translate to 95 / 32 which produces 2,96875, but since we are dealing with integers, it's simply 2 regardless of how small the difference is. So that is why my player is in column 2 instead of 3 and why I check the two tiles below the player. I fix this in the if statement where I set the fall variable.
There are one or two more bugs, but I have "fixed them".
Anyway, sorry for wasting your time, but I had to explain why I did what I did. Now I would like to ask how to implement proper physics, not realistic, something like Mario physics but without an engine? My knowledge of physics in real life are lacking, I slept or skipped physics classes in school, so it's as if I know nothing. 
I've been looking at some articles online, but I didn't understand how to implement things like deceleration, jumping force based on how long the space bar was pressed. Or to do gravity properly.
Edited by farmdve

Share this post

Link to post
Share on other sites

Basically, each object has a location on each axis, a velocity (speed) on each axis, and accelaration on each axis.


To put it simply in terms of game programming, location is where the object is. (Obviously)


Velocity will tell you where the object is going to be in the next frame.

[Example: if your object is at x=2, and has a velocity of 2, the next frame it's going to be at  x=4 (2+2) and the frame after that x=6 (4+2)]

So on each frame (or game loop) you just add the location on an axis to the velocity of that axis before drawing it.


Accelartion will tell you what the object's velocity is going to be in the next frame.

[Example: if your object's velocity is 2, and has an accelaration of 2, the next frame the velocity is going to be at  4 (2+2) and the frame after that it will be 6 (4+2)]

So on each frame (or game loop) you just add the velocity on an axis to the accelaration of that axis before drawing it.


Force directly affects accelaration.

So if you want gravity (a force) you need to have an accelaration on y axis downwards at all times.

If you want jumping (a force) you need to have an accelaration on y axis upwards while the jump button is being pressed.

While in reality running is a kind of force, game developers usually directly alter the velocity on x axis rather than the acceleration for simplification. (Sometimes the jumping is also achieved by altering velocity rather than accelaration.)


So on your game loop you'll have something like this (The following is a simple psudo code)

Draw object on loc.x and loc.y;

On keypresses you can alter the velocity and acceleration rather than the loc.x and loc.y. To have gravity, always have a downwards acc.y and if you wanted to alter acc.y, add it up to this number rather than changing it.


I'm not sure how to implement that in your game, because collision detection is an entirely different issue. I suggest you get this basic physics model on another project until you get it working, and then implementing the same thing in your game.

Edited by gezegond

Share this post

Link to post
Share on other sites

I don't see any speed attribute on your code. Are you hardcoding the acceleration and speed of your player? Altering the position directly?


You can include in your player class/structure some sort of physics struct that includes everything relevant, or.

typedef struct physics_structure {
    float speed[2]; //0 = X and 1 = Y
    float position[2];
} phys;

This way, you can make the jump as:

speed[1] += 2000 //increment speed on y axis with a desired number

And then you apply gravity as a decrement on speed that happens every frame, unless he's in direct contact with a tile.

Edited by dejaime

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
Sign in to follow this  
Followers 0