February 20, 2010

Simple 2D Gravity In Games [Explanation]

Introduction

Sometimes understanding gravity can be hard.
I mean, yeah, it's always around us, it's always been there. But when trying to fake gravity into games- platformers is my example- it can sometimes get confusing. After this article, I hope you'll know how to implement gravity in any language- and since gravity is basically math, I'm not going to recommend a particular programming language you should use to write it.

What's better to start than pull up a definition of gravity? So here's one, located here:
gravitational force: the attraction due to gravitation that the Earth or another astronomical object exerts on an object on or near its surface
We obviously don't have 'Earth' in our game per say, but we know it has to do with attraction. Let's keep this in mind and move on.

(I know the image sucks). Above is a basic representation of gravity. Something is forced up, and gravity acts on it and it moves down gradually. How do we represent this change using math? Well, we’ll need to define gravity of course…

To the basics

I'm going to start be representing super-basic gravity. We'll draw an image and make it move down at an increasingly fast pace, just like in real life.
//Declare gravity and add it to character
float gravity = 0.1f;
character.Y += gravity;
//To make it drop increasingly fast
gravity += 0.1f;

Now that we've done that, we can study the code. I first declare gravity, and assign it as 0.1 (the f is to show it's a float/decimal number, depends on the programming language). Next, I add gravity to the character's Y position (note here that sometimes you might have to subtract y to make it go down) and finally increase gravity so it keeps falling faster. A lot of games I notice actually don't have this feature, and it all comes down to the matter of what you want.

Limiting Gravity

The example above is good and all, but it drops increasingly fast until it's wayyy too fast. I'm going to fix that by simply adding a check:
if (gravity > 0.4f) {
gravity = 0.4f; 
}
There we have it. Super basic gravity.

Using Velocity

I’m going to use velocity in the following examples. Velocity is the rate of change in the position of an object as it moves in a particular direction. We can use velocity coupled with gravity so we can actually travel in an ark- as it can take account of the current direction and add gravity on top of that.

Here’s some code showing that:

Vector2 velocity;
float gravity = 0.1f;

if (keyPressed==Keys.Right) {
velocity = 3.0f;
}
velocity.Y += gravity;
mainChar.X += velocity.X;
mainChar.Y += velocity.Y;
Basically what I am doing here is creating a vector (this is basically a multi-dimensional array, can be replaced by two float/decimals) and, responding to key presses, adding the velocity to the main character’s X and Y. By doing this, I can set multiple velocity increases and have it all affect the character similarly. Now I can easily code things like springs.

Conclusion

Here concludes my gravity tutorial. I’ll be writing a tutorial on jumping next! It's up! If you have any questions, comments, or concerns, remember to leave me a comment. If you enjoyed the post, remember to Subscribe to my RSS feed. Or email me at finaiized(at)gmail.com if you want. I'm welcome to all suggestions you may have, and am willing to help you.

40 comments:

  1. great tutorial, thanks for braking it down to make it simple and easy to apply to any situation.

    ReplyDelete
  2. Nice Job. However, vector is a one dimensional array, not multidimensional.

    ReplyDelete
  3. Great article.. but why 0.8 and 0.1?
    are these related to gravity low or something?

    ReplyDelete
  4. A big thank you for your blog article. Really Cool. gamerbolt

    ReplyDelete
  5. Easily, the article is actually the best topic on this registry related issue. I fit in with your conclusions and will eagerly look forward to your next updates. Eric

    ReplyDelete
  6. Very interesting blog. Alot of blogs I see these days don't really provide anything that I'm interested in, but I'm most definately interested in this one. Just thought that I would post and let you know. coin master free spins

    ReplyDelete
  7. Really I enjoy your site with effective and useful information. It is included very nice post with a lot of our resources.thanks for share. i enjoy this post. fortnite free v bucks generator

    ReplyDelete
  8. I think that thanks for the valuabe information and insights you have so provided here. AGe of Empires

    ReplyDelete
  9. I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article. best typing softwares
    I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article. best typing softwares

    ReplyDelete
  10. I havent any word to appreciate this post.....Really i am impressed from this post....the person who create this post it was a great human..thanks for shared this with us.
    gta 5 download

    ReplyDelete
  11. After reading your article I was amazed. I know that you explain it very well. And I hope that other readers will also experience how I feel after reading your article. games for blind kids

    ReplyDelete
  12. I feel very grateful that I read this. It is very helpful and very informative and I really learned a lot from it. games for blind people

    ReplyDelete
  13. I wanted to thank you for this excellent read!! I definitely loved every little bit of it. I have you bookmarked your site to check out the new stuff you post. check my blog

    ReplyDelete
  14. Great post, and great website. Thanks for the information! https://w88coid.com/cam-nang-ca-do

    ReplyDelete
  15. This is such a great resource that you are providing and you give it away for free. I love seeing blog that understand the value of providing a quality resource for free. Bolt Posts

    ReplyDelete
  16. Video gaming transports members to unidentified globes and truths and can teach us brand-new things each and every day. There actually are some remarkable perks to video gaming. If you remember the insight above, you will appreciate it more and be more skilled.안전놀이터

    ReplyDelete
  17. Wow, What an Outstanding post. I found this too much informatics. It is what I was seeking for. I would like to recommend you that please keep sharing such type of info.If possible, Thanks. Generator

    ReplyDelete
  18. The most they will give is an educational portrayal, their social records, client audits and recordings by them.
    CS GO professional League

    ReplyDelete
  19. Online slot games are a lot of renowned among the web shrewd people who extravagant this charming game of karma and receive a great deal of rewards of playing on the web thus. How To Win playing slots

    ReplyDelete
  20. We should make a plunge directly into what is seen as negative about gaming. Most of the pessimistic things about games come from the genuine individuals on those games, the sort of games and the kinds of games for some unacceptable individual. 홀덤

    ReplyDelete
  21. After choosing your CPU, next you need to consider choosing your motherboard for your gaming computer. When selecting a motherboard, you should remember three things. go to this site computer games

    ReplyDelete
  22. Tencent Gaming Buddy is a popular Android emulator" for PUBG fans and allows you to also play several other Android games on your Windows PC.endoscope app for pc mac

    ReplyDelete
  23. One can't disregard Hearthstone with regards to the best games you can play on a PC! A collectable game set in Blizzard's Warcraft universe, you'll be battling against different players with sorcery spells, weapons, followers and unique capacities. Pc games

    ReplyDelete
  24. This comment has been removed by the author.

    ReplyDelete
  25. These are a portion of the advantages of playing computer games. On the off chance that you need to have a more charming playing experience, there are various sites that you can visit.ApkDyno.com

    ReplyDelete
  26. Additionally, it gives brushless engine which can give simple development with no erosion. The point change differs from 270 to 1080 degrees in regards to the game vehicle.Download Games

    ReplyDelete
  27. This altered framework depends on 11 catches which can without much of a stretch control all the programing later on gaming like which will be dispatched in the 2018. Aside from this, it is the best gaming gadget since it is not difficult to convey with light weight of the 3.6 gram alongside agreeable plan for me to use as it has hold too. games unblocked

    ReplyDelete
  28. A Theory of Fun for Game Design, Raph Koster characterizes a game to be an intelligent encounter that furnishes the player with an inexorably difficult arrangement of examples which the person learns and in the end aces. buy guns of glory resources

    ReplyDelete
  29. Sporting events which incorporate playing on the web an assortment of sports like cricket, soccer, volley ball, equation one race, etc. The player needs to comprehend the genuine game to play online sporting event. The games permit testing of exactness and precision of the player. Online sporting events are well known and cutthroat like genuine games. slope y12

    ReplyDelete
  30. This Android game depends on the early hypothesis that you could take existing components and make gold with them. homepage

    ReplyDelete
  31. Tennis for Two" was made by William Higinbotham, a physicist working at the Brookhaven National Laboratory. This game was made as a method of amusement, so research center guests had something entertaining to do during their look out for "guests day" (finally!... a video game that was made "only for fun"...) . https://twitchviral.com/

    ReplyDelete
  32. This altered framework depends on 11 catches which can undoubtedly control all the programing later on gaming like which will be dispatched in the 2018. Click Speed Test

    ReplyDelete
  33. The Champs Selections. In this article, I will give a little foundation on the Sports Betting Champ, John Morrison, and survey a portion of his items. poker qq terpercaya

    ReplyDelete
  34. Nonetheless, there are incalculable gaming peripherals of consoles however Logitech G Pro Keyboard is one of the most outstanding gaming gadgets. SimCity Buildit hack

    ReplyDelete
  35. Hi there! Nice post! Please tell us when I will see a follow up! 꽁머니사이트

    ReplyDelete
  36. handicappers picked Atlanta to dominate the match (Robert Ferringo, Gamblers Data, The Shark, Kelso Sports Handicapping, Dr Baseball) 토토사이트

    ReplyDelete
  37. Kids are innately curious animals. They have an oddity to find new things and learn via finding and testing even before they are exposed to techniques for formal training like perusing or composing.online games

    ReplyDelete
  38. In this contemporary world, it has become responsible to get to each and everything with current advances; accordingly, gaming peripherals are the best gaming gadgets which solace the gamers who love to play the best games with simple and open gadget to play their abilities. 온라인카지노

    ReplyDelete
  39. handicappers picked Arizona to dominate the match (#1 Sports, Profit-On-The-Net, Super Sports Group, Kiki Sports) 꽁머니 2만

    ReplyDelete