Home » Source Code » Gravity and Collision Simulation in C#

## Description

Translated by maninwest@Codeforge Author:Suhib N. Rawshdeh@CodeProject
Simulating the motion of an object within a real time environment with Gravity and Collision effects may not be a straightforward task in ordinary programming languages; doing such tasks require a good understanding of using timers and sometimes thread management, and this is why there are separate simulation tools for this and other similar tasks.
In this article, I will demonstrate to you how, using a timer and basic motion and collision equations, we could model the motion of three balls in a gravity enabled environment. You will see how these balls are going to collide each other and reflect from a wall, and even more, you can control their motion by updating some motion variables.
The motion of these balls is controlled and operated under the gravity and collision systems, using Newton's basic motion equations and collision equations. The positions of the three balls are updated every 20ms using a timer which will also take a snapshot of that motion.
Background
Before you see the code, I believe we should review the basic Gravity and Collision equations first.
Theoretical Analysis:
Gravity and motion equations:
The position equation:
X = Xi + Vx * tx
Xi: Is the initial position of the object.
Vx: Is a constant speed if we ignore the friction and air resistance, which I do include in this simulation. I consider the air as a constant resistance that must be taken care of periodically, so I divide the motion into separate periods and calculate the new position for each period.
tx: Is the time.
Motion third equation:
Y = Y0 + Vy * ty – 0.5 * g * t^2
g: The gravity acceleration.
The velocity equations:
Vy = Vy0 – g*t
Vy: The final Y speed.
Vy0: The initial Y speed.
g: The gravity acceleration.
Vx = 0.99*Vx0
Vx0: The old X speed.
Vx: The new X speed after including air resistance.
0.99: Is a constant ratio representing air resistance.
Collision and preserved momentum:
Collision: an action between two or more bodies, each one affecting the others by a great power in a very short time, the bodies might not even touch!!!
+ Notes:
• The two bodies may be moving in opposite directions.
• The two bodies may be moving in the same direction.
• One is moving while the other is still.
• The power at the time of collision between two bodies can be represented as shown in the graph below:

Collision power

If two or more bodies collide, then the sum of their momentum before the collision is equal to the sum of their momentum after the collision.
Theory:
```V1×m1 + V2×m2 = V1`×m1 + V2`×m2

Assuming same mass:
V1 + V2 = V1` + V2````

Collision

The code below will clarify these equations in their context.
Using the code

First of all, we should define the motion variables for each ball in our simulation.
```///////////////////////////////////////// ball /////////////////////////////////////
// xspeed: The X axis speed of the ball –                                         //
//           it will be calculated based on the mouse movement speed.             //
// yspeed: The Y axis speed of the ball –                                         //
//           it will be calculated based on the mouse movement speed.             //
// newyspeed: The updated Y acis speed of the ball                                //
//              after applying Newton and collision equations.                    //
// startingypos: The initial Y position of the ball –                             //
//               when stop dragging the ball.                                     //
// newxpos: The updated X position of the ball                                    //
// newypos: The updated Y position of the ball                                    //
// oldxpos: The previous X position of the ball                                   //
// oldypos: The previous Y position of the ball                                   //
// newx: The new X position of the mouse after dragging                           //
// oldx: The old X position of the mouse after dragging                           //
// newy: The new Y position of the mouse after dragging                           //
// oldy: The old Y position of the mouse after dragging                           //
// acc: The acceleration = 10                                                     //
// t: The time                                                                    //
// xmouse: The X axis of the mouse pointer position                               //
// ymouse: The Y axis of the mouse pointer position                               //
// dragging: Boolian variable to check whether the ball is being dragged or not.  //
// trace: Boolian variable to check if the trace option is on or off.             //
// collisiony: Boolian variable to check if the ball hits the ground or not.      //
////////////////////////////////////////////////////////////////////////////////////

// ball 1 variables
double xspeed,yspeed,newyspeed,startingypos;
double newxpos,newypos,oldxpos,oldypos;
double newx,oldx,newy,oldy;
double acc,t;
const int ground = 500;
int xmouse,ymouse;
bool dragging=true,trace,collisiony;

int choice = 1;
int numberofballs = 1;

Ballinstance b1 = new Ballinstance();```

Next, we will track the ball motion and check for a collision every 20 ms in our timer, and accordingly we will update the balls' positions.
```private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
b1.play(ref xspeed,ref yspeed,
ref newyspeed,ref startingypos,
ref newxpos,ref newypos,ref oldxpos,ref oldypos,
ref newx,ref oldx,ref newy,ref oldy,
ref acc,ref t,
ref xmouse,ref ymouse,
ref dragging,ref trace,ref collisiony);
ball.Left = (int)newxpos;
ball.Top = (int)(ground - newypos);

Collision();
}```

Below is theBallinstanceclass, and theplayfunction where most of the work is done. As you will see, this function will be visited every 20 ms, the timer period, and then will check for the calling ball status, which can be as follows:
Dragging state:
If the ball calling theplayfunction was in the drag mode, then the ball position will be updated according to the mouse pointer position, and the ball's initial speed will be calculated by measuring the change of the ball position between two successive calls to theplayfunction; within 20 ms.
Motion state:
If the ball calling theplayfunction wasn't in the drag mode, then the ball position will be updated according to Newton's and projectile motion equations and the Collision preserved momentum equation.
```private void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
{
b1.play(ref xspeed,ref yspeed,
ref newyspeed,ref startingypos,
ref newxpos,ref newypos,ref oldxpos,ref oldypos,
ref newx,ref oldx,ref newy,ref oldy,
ref acc,ref t,
ref xmouse,ref ymouse,
ref dragging,ref trace,ref collisiony);
ball.Left = (int)newxpos;
ball.Top = (int)(ground - newypos);

Collision();
}```

Conclusion

The project is not completed yet. I was thinking of creating some obstacles to see how the balls will collide them, seems funny Smile | :) . You also can improve the way it looks and make it more usable if you write a routine to drag and drop the ball by grapping it, which I can't find out how to do in C#!!
I'd like to thank Anas Trad and Du3a2 Al-ansari, my friends, for their contributions to help finish this simulation.

## File list

Tips: You can preview the content of files by clicking file names^_^
Name Size Date
Gravity96.00 kB2007-12-25 13:05
...

Minimum:15 words, Maximum:160 words
2016-01-22

i will change some things

f781976192
2016-09-27

• 1
• Sent successfully!
• GravitySimulation_demo.zipGravitySimulation_src.zip
• 1 Point(s)

### Gravity and Collision Simulation in C#(13.03 kB)(15.66 kB)

Need 1 Point(s)

Get 22 Point immediately by PayPal

More(Debit card / Credit card / PayPal Credit / Online Banking)

Submit your source codes. Get more Points

Don't have an account？ Register now
Need any help?
Mail to: support@codeforge.com

### 切换到中文版？

CodeForge Chinese Version
CodeForge English Version

### ^_^"Oops ...

Sorry!This guy is mysterious, its blog hasn't been opened, try another, please!

### Warm tip!

Favorite by Ctrl+D