# How do I add gravity to a game?

• (3 Pages)
• 1
• 2
• 3

## 32 Replies - 12444 Views - Last Post: 08 December 2011 - 09:01 PMRate Topic: //<![CDATA[ rating = new ipb.rating( 'topic_rate_', { url: 'http://www.dreamincode.net/forums/index.php?app=forums&module=ajax&section=topics&do=rateTopic&t=258839&amp;s=19d8e3fbaf4c2842f35650b3759930b2&md5check=' + ipb.vars['secure_hash'], cur_rating: 0, rated: 0, allow_rate: 0, multi_rate: 1, show_rate_text: true } ); //]]>

### #1 The_Programmer-

• C++ Apprentice

Reputation: 25
• Posts: 646
• Joined: 24-October 11

# How do I add gravity to a game?

Posted 06 December 2011 - 10:55 PM

I'm in High School Honors Geometry and I am half way through the year so I might not understand everything. Could someone link me to a tutorial where you can just make a ball drop and it applies gravity and the ball bounces?
Is This A Good Question/Topic? 0

## Replies To: How do I add gravity to a game?

### #2 macosxnerd101

• Self-Trained Economist

Reputation: 11034
• Posts: 41,275
• Joined: 27-December 08

## Re: How do I add gravity to a game?

Posted 06 December 2011 - 10:58 PM

I have a tutorial on 2D gravity.

From a basic algebra perspective, just parameterize x and y both as functions of time. Then use the kinematics equations:
x(t) = x0 + v*t + 1/2 * at^2
y(t) = y0 + v*t - 4.9t^2 (g = -9.8 m/s^2)

### #3 Mylo

• Knows all, except most.

Reputation: 265
• Posts: 747
• Joined: 11-October 11

## Re: How do I add gravity to a game?

Posted 06 December 2011 - 11:08 PM

Just what I wanted mac, well I don't need it, but I will someday and it certainly interests me. I'll give that a read thanks.

### #4 The_Programmer-

• C++ Apprentice

Reputation: 25
• Posts: 646
• Joined: 24-October 11

## Re: How do I add gravity to a game?

Posted 06 December 2011 - 11:08 PM

macosxnerd101, on 06 December 2011 - 09:58 PM, said:

I have a tutorial on 2D gravity.

From a basic algebra perspective, just parameterize x and y both as functions of time. Then use the kinematics equations:
x(t) = x0 + v*t + 1/2 * at^2
y(t) = y0 + v*t - 4.9t^2 (g = -9.8 m/s^2)

Yeah... I didn't really understand your tutorial. I'm only a sophomore in high school so you would have to explain what every single variable is.

### #5 macosxnerd101

• Self-Trained Economist

Reputation: 11034
• Posts: 41,275
• Joined: 27-December 08

## Re: How do I add gravity to a game?

Posted 06 December 2011 - 11:08 PM

@The_Programmer-: Let's start with a simple x-y graph. Are you familiar with Cartesian graphs of functions? They relate x and y, and generally y is a function of x. You may have seen f(x) = y = 3x. So what we are doing is treating x and y independently. The x and y variables are related to time. So x(t) = 3t, and y(t) = someInitialYPosition + yVelocity*t - 4.9t^2.

The general form kinematics equation is (where r is position):
r(t) = rInitial + v*t + 1/2 a*t^2
v = velocity
a = acceleration

Gravity accelerates the particle. Since gravity points downwards and the positive y direction is upwards, you subtract the acceleration due to gravity from the position. So:
y(t) = yInit + v*t - 4.9t^2

Then you plot the object at the x and y coordinates for the given time value.

Does that make more sense?

### #6 The_Programmer-

• C++ Apprentice

Reputation: 25
• Posts: 646
• Joined: 24-October 11

## Re: How do I add gravity to a game?

Posted 06 December 2011 - 11:15 PM

macosxnerd101, on 06 December 2011 - 10:08 PM, said:

@The_Programmer-: Let's start with a simple x-y graph. Are you familiar with Cartesian graphs of functions? They relate x and y, and generally y is a function of x. You may have seen f(x) = y = 3x. So what we are doing is treating x and y independently. The x and y variables are related to time. So x(t) = 3t, and y(t) = someInitialYPosition + yVelocity*t - 4.9t^2.

The general form kinematics equation is (where r is position):
r(t) = rInitial + v*t + 1/2 a*t^2
v = velocity
a = acceleration

Gravity accelerates the particle. Since gravity points downwards and the positive y direction is upwards, you subtract the acceleration due to gravity from the position. So:
y(t) = yInit + v*t - 4.9t^2

Then you plot the object at the x and y coordinates for the given time value.

Does that make more sense?

Yeah, it makes more sense but I'm not completely sure. I know this might be asking a lot or you might not be able to do it because it would be giving away code, but could you write some example class that I could look at and see what everything does?

### #7 macosxnerd101

• Self-Trained Economist

Reputation: 11034
• Posts: 41,275
• Joined: 27-December 08

## Re: How do I add gravity to a game?

Posted 06 December 2011 - 11:36 PM

Honestly, I think a graphic might be better than a code sample here. If you can understand how it works on a Cartesian graph, then programming it is the easy part. A lot of this math you will get in trig/pre-calculus, physics, and calculus. Really, the trig and pre-calc is good for abstracting a lot of it.

The idea is to treat the x and y coordinates separately. When you calculate the slope of a line, you divide the change in y over the change in x: m = (y2 - y1)/(x2-x1). So what you want is to look at deltaX = (x2-x1) and deltaY = (y2-y1) separately. The object's movement in the x-direction is not affected by gravity. Only the y-direction is affected by gravity.

I've put together a graph below, which describes the motion of gravity. Notice it is a curve pointing downwards. In order for an object to move in the positive y-direction, it's y-velocity (vy) has to be greater than 0. This is what you want to deal with in your program- when an object moves upwards, it's y-velocity is positive. Now, gravity pulls down on an object, so it is a negative quantity. However, gravity is acceleration, not velocity. Remember that acceleration says how much the velocity is changing.

There will come a point on the graph where the y-velocity = 0. This is the point at the maximum height. However, since gravity is still acting on the object, the acceleration is still negative, thus causing the object to fall. Think about it that way.

Hence why we have the equations:
x(t) = xInit + vX*t
y(t) = yInit + vY*t - 1/2 *a * t^2 (a = g = 9.8 m/s^2 when dealing with gravity)

### #8 The_Programmer-

• C++ Apprentice

Reputation: 25
• Posts: 646
• Joined: 24-October 11

## Re: How do I add gravity to a game?

Posted 06 December 2011 - 11:42 PM

Ok. I think I'm understanding it now. I'm just not sure on the equations you have but I understand everything else. I have to go so I will post in the morning. I will also try out a program in the morning.

### #9 macosxnerd101

• Self-Trained Economist

Reputation: 11034
• Posts: 41,275
• Joined: 27-December 08

## Re: How do I add gravity to a game?

Posted 06 December 2011 - 11:53 PM

Let's work through it a little. Say we start at (0,0) with an xVelocity of 10 m/s and a yVelocity of 15 m/s. Our acceleration due to gravity is 9.8 m/s^2. So:
x(t) = 0 + xVelocity * t
y(t) = 0 + yVelocity * t - 1/2 * a * t^2

At t = 0, x = 0 and y = 0. Let's look at how our x and y values change:
```t       x        y
0.5     5       6.275
1       10      10.1
1.5     15      11.475
2       20      10.4
2.5     25      6.875
3       30      0.9

```

Notice how the y increases, then decreases. At some point between t = 1.5 and t = 2, the y-velocity = 0 and the object is at its highest point. Then somewhere right after t = 3, the y-velocity = 0 and the ball touches the ground. You can get the exact time values by solving the quadratic equations (which you may not have covered at this point in your math career).

### #10 The_Programmer-

• C++ Apprentice

Reputation: 25
• Posts: 646
• Joined: 24-October 11

## Re: How do I add gravity to a game?

Posted 07 December 2011 - 10:57 AM

OK. I understand everything now. But why do you add time squared to the y velocity? And is time in milliseconds? seconds?
Edit: And I guess I don't understand everything because does x(t) mean x(at a certain time)?

This post has been edited by The_Programmer-: 07 December 2011 - 11:13 AM

### #11 The_Programmer-

• C++ Apprentice

Reputation: 25
• Posts: 646
• Joined: 24-October 11

## Re: How do I add gravity to a game?

Posted 07 December 2011 - 11:20 AM

I also studied quadratic equations but I have forgot what they are now.

### #12 macosxnerd101

• Self-Trained Economist

Reputation: 11034
• Posts: 41,275
• Joined: 27-December 08

## Re: How do I add gravity to a game?

Posted 07 December 2011 - 11:42 AM

I add 1/2 * a * t^2 to the y position. There is some Calculus involved in deriving this, but the conceptual explanation is that acceleration determines how much the velocity changes. So acceleration/2 * t^2 + v*t gives the new position at time t, assuming constant acceleration.

Quote

And I guess I don't understand everything because does x(t) mean x(at a certain time)?

This is just like a function f(x). When you see x(t), we are referring to elapsed time. So we start at t = 0.

### #13 The_Programmer-

• C++ Apprentice

Reputation: 25
• Posts: 646
• Joined: 24-October 11

## Re: How do I add gravity to a game?

Posted 07 December 2011 - 11:56 AM

macosxnerd101, on 07 December 2011 - 10:42 AM, said:

I add 1/2 * a * t^2 to the y position. There is some Calculus involved in deriving this, but the conceptual explanation is that acceleration determines how much the velocity changes. So acceleration/2 * t^2 + v*t gives the new position at time t, assuming constant acceleration.

Quote

And I guess I don't understand everything because does x(t) mean x(at a certain time)?

This is just like a function f(x). When you see x(t), we are referring to elapsed time. So we start at t = 0.

Thanks for everything. Using all of this, I will try to make a simple program that drops a ball or throws it or something. My next step would be to add friction and stuff so the ball will bounce around the screen.

### #14 The_Programmer-

• C++ Apprentice

Reputation: 25
• Posts: 646
• Joined: 24-October 11

## Re: How do I add gravity to a game?

Posted 07 December 2011 - 03:09 PM

Okay. I have the beginning of my program lined out but I have no idea how to build the methods for changing the x and y value. Sorry if I included too little in this outline program.
```package me.kennth.gravitysim;

import java.awt.BorderLayout;

import javax.swing.*;

public class Main extends JFrame {

private static final long serialVersionUID = 1L;
MyPanel panel;

private Main(boolean isResizable, String title) {

super(title);
setLayout(new BorderLayout());
panel = new MyPanel();
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(500, 500);
setResizable(isResizable);
setVisible(true);
panel.startSim();

}

public static void main(String[] args) {

new Main(true, "Gravity Simulator");

}

}
```

```package me.kennth.gravitysim;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.math.*;

public class MyPanel extends JPanel implements ActionListener {

private int x, y, dx, dy, velocity;
private final double RATE_OF_ACCELERATION = 9.8;

public MyPanel() {

x = 100;
y = 250;
dx = 0;
dy = 0;
velocity = 15;

setDoubleBuffered(true);
setPreferredSize(new Dimension(500, 500));
setIgnoreRepaint(true);

}

public void startSim() {

while (true) {

}

}

public void paintComponent(Graphics g) {

super.paintComponent(g);

}

}
```

### #15 The_Programmer-

• C++ Apprentice

Reputation: 25
• Posts: 646
• Joined: 24-October 11

## Re: How do I add gravity to a game?

Posted 07 December 2011 - 04:07 PM

Well I made a prototype. It seems to only go diagonal and it is kind of cheesey how it falls... And how could I add borders?
```package me.kennth.gravitysim;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;

public class MyPanel extends JPanel implements ActionListener {

private static final long serialVersionUID = 1L;
private int x, y;
private double timeValue, velocity, dx, dy;
private final double RATE_OF_ACCELERATION = -9.8;
Timer time;

public MyPanel() {

x = 100;
y = 250;
dx = 0;
dy = 0;
velocity = 1;
timeValue = 0;
time = new Timer(16, this);

setDoubleBuffered(true);
setPreferredSize(new Dimension(500, 500));
setIgnoreRepaint(true);
setBackground(Color.WHITE);

}

public void startSim() {

time.start();

}

public void paintComponent(Graphics g) {

super.paintComponent(g);

g.setColor(Color.WHITE);

g.fillRect(0, 0, 500, 500);

g.setColor(Color.BLUE);

g.fillOval(x, y, 20, 20);

g.dispose();

}

public void actionPerformed(ActionEvent e) {

timeValue += 0.01;
dx = 0 + velocity * timeValue;
dy = 0 + velocity * timeValue - (1 / 2) * RATE_OF_ACCELERATION * (Math.pow(timeValue, 2));

x += dx;
y += dy;

repaint();

}

}
```