Jump to content

  • Log In with Google      Sign In   
  • Create Account

We need your feedback on a survey! Each completed response supports our community and gives you a chance to win a $25 Amazon gift card!


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


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
2 replies to this topic

#1 farmdve   Members   -  Reputation: 194

Like
0Likes
Like

Posted 26 October 2013 - 01:52 PM

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.

 

 

Untitled.jpg

 

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;

    }    

    

    if(fall)

    {

        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

 

pic1.jpg
 
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, 26 October 2013 - 01:56 PM.


Sponsor:

#2 gezegond   Members   -  Reputation: 373

Like
1Likes
Like

Posted 26 October 2013 - 03:42 PM

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)

vel.x+=acc.x;
vel.y+=acc.y;
loc.x+=vel.x;
loc.y+=vel.y;
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, 26 October 2013 - 03:42 PM.


#3 dejaime   Crossbones+   -  Reputation: 4119

Like
0Likes
Like

Posted 26 October 2013 - 05:32 PM

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, 26 October 2013 - 05:33 PM.





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS