Basic Vectors and Physics

advertisement
Written by Patrik Strandell - mail: Patrix@Truplo.com
Last Edit:
February 6, 2016
Vectoring it up – The basic of Vectors and Physics
About this Article
This is an article about vectors and game physics. It is supposed to give you a good base
for understanding on how vector physics works in general and how you later can use them in
your game. The basics of vectors are pretty simple and they provide a powerful way to add
physics to your game. Here I will address what vectors are and how you can make use of
them to describe simple physics. I will assume you know the basics of math and the basics
of programming while I will assume you don’t know “any” physics. The examples are coded in
BlitzMax (see www.blitzmax.com).
Why use vectors?
The reason to use vectors is mainly to simplify mathematical calculations. The vectors don’t
cut the amount of math done by the computer, but it’s a very good way to cut the amount
of math we need to do and write ourselves. This tutorial will help you realize their
simplicity and potential, and give you a good base to build upon which will help you the day
you decide to add more advanced physical effects to your game, whether you mimic reallife physics or make up your own.
Where is vectors used?
Vectors are first and foremost used in science and programming. This could be games,
quantum physics, any simulations, 3D graphics and mathematical theories. You probably
already use them in your game, unaware of the fact that any movement can be (or are)
described with vectors. Also do not forget that 3D graphics are built on the very
foundation of vectors and projections of vectors. It may look 3D but obviously it is still
(most likely) displayed on a flat 2D screen. That transformation from 3D to 2D is done
with heavy vector calculations. Read on and you will be well on your way to knowing the full
potential of vectors!
What do they do?
Vectors show velocity, force and acceleration and they make it very easy to work with
these. To describe a force or acceleration you can’t just use a number. The number only
tells you how much we are accelerating, you also have to know from where or to where.
Here is where vectors have to be used, because they also specify the direction. With
vector we can simplify and say our acceleration is V or A, and if we want to combine two
accelerations we just add them V + A = T. Many of the quantities in physics such as
velocity, acceleration and force require both an amount and a direction to be fully
described; therefore vectors are used to fully describe these quantities. A vector also has
the unique ability to exist in any number of dimensions. Lost? No worries, it will become
clear soon enough, keep reading!
1
Written by Patrik Strandell - mail: Patrix@Truplo.com
Last Edit:
February 6, 2016
What is a dimension?
The use of dimensions (or rooms), is way to describe the world and space around us. To
understand the concept of dimensions I suggest we start with some examples of how our
world would look like in different dimensions and how we in each dimension would do to
specify a location.
Point in one dimension (1D)
Imagine you are a train and that you are traveling on a railroad. In this world you can not
steer left or right. For you there is only forwards or backwards. Where you are; your
location, can be described by how far away you are from a train station. To describe your
movement we use a value which tells us your speed. Negative if you travel backwards.
Positive if you go forward. Any point on the railroad can in other words be described by a
number that says how far away from any other point on the rail. 1D problems are very
important because they are so simple and many 2D and 3D problems can be simplified and
solved in 1D.
Point in two dimensions (2D)
In two dimensions we have a field, grid or plane instead of a linear rail. Imagine yourself
playing a game of chess. You play on a grid of 8 squares wide and 8 squares high. Every
square of the grid can be determined by combining the length (in squares) of a game piece
if from the top left corner of the grid. Example: Your King is at E3. We know it is 3
squares up and E squares left, where E represents the fifth letter. In a computer that
would mean location (3,5). Let us also take your screen as an example. You are probably
aware of its resolution. The resolution is the amount of pixels that fits on the screen. So
your screen is a grid of pixels. With the top left corner (also referred to as the origin)
being (0, 0). The bottom-right pixel would be your resolution, which, for example, could be
(1024, 768) or (1600, 1200).
Point in three dimensions (3D)
If we want to know an object’s location in three dimensions, think a fish in a simple square
transparent aquarium. The bottom of the aquarium has a flat 2D surface. In this case our
aquarium just happens to have the same size as our chess board. So imagine putting the
aquarium on top of the chess board and don’t forget to remove the pieces. Now if we look
from the top down into our aquarium we see a chess board. Fill the aquarium with water if
you haven’t already and put a little fish in there. To determine the location of the fish or a
specific point in the aquarium we can simply look at our chess grid. My fish is in square D5.
D is the letter five, so with coordinates (4, 5). Wait! There is something missing! We don’t
know the height of the fish from the bottom! No problem, we easily can measure the fish
swimming 3 “chess grids” above the bottom which makes its height coordinate equal to 3.
So our fish’s coordinates in three dimensions is ( 4, 5 ,3 ) - ( X, Y, Z) respectively. X is the
amount of squares from the left of the board. Y is the squares from the top of the board
and Z is the height of the fish from the bottom.
2
Written by Patrik Strandell - mail: Patrix@Truplo.com
Last Edit:
February 6, 2016
Point in four dimensions (4D)
I guess the easiest way to describe this is to use time as the fourth dimension. Simply note
the time in which the fish where at a certain location and you have 4D: ( X, Y , Z , time). In
other words we have a vector with four fields; four dimensions. Just consider that our
measurement of time is different to our measurement of space. Anyhow I will not dwell
deeper into it.
Point in five or more dimensions
We can keep adding dimensions, mathematically it’s not a problem, but it will be hard to
visualize and we won’t have any use for it today. I’ll only work with two dimensions to show
you physics and vectors here.
Vectors in 2D
You may visualize a vector in 2D as an arrow; a line from one point to another. In opposite
to a line, the vector itself does not contain any data of where it begins or ends. The vector
is merely the difference between these two points.
When you work with vectors in school you will write them like
this A= (2,3). A is the vector, 2 and 3 are the values of the
vector; 2 is the length of the vector in X and 3 the length in Y.
It’s common to show that a variable is a vector by writing it in
bold or having a line or arrow over it. I’ll write vectors as bold
letters.
For example, when you update the movement of your player in your game you add to his x
and y position. To go from X=2 to X=3 you add 1 to X. If you want to go from Y=2 to Y=4
you add 2 to y. This movement can be described as the difference from the start point to
the end point. Instead of adding one to X and two to Y we
Origin
combine them and we add a vector called (1, 2) to our
X
(0,0)
current position. (1,2) is the vector seen in the picture to
the right. Where this vector start we don’t know. We can
(2,2)
move this vector however we want, as long as we keep its
direction and length. If you move the vector in the
picture to (1,1) the end-point of the vector would point to
(3,4)
(2,3). The vector itself would still remain the same; (1, 2).
Y
Say our acceleration from a thruster is vector A. If we
want to combine A with the acceleration from gravity G, we could add them G + A = T
3
Written by Patrik Strandell - mail: Patrix@Truplo.com
Last Edit:
February 6, 2016
where T is the resulting acceleration vector. Note that the direction of the gravity often
point downwards, but this does not mean gravity is a negative force. The length of a vector
can never be negative. Therefore, when we add a vector that points down with a vector
that point left we simply get a vector that points down-left. However also note that the
values of the vector can be negative.
In the end we added the vectors length and direction and got a vector somewhere in
between. I’ll now show how to add vectors mathematically.
Vector Math : Addition
A and B are 2D vectors. A = (2, 4) and B = (3, 5). If we wish to add them we add the X and
Y values separate. A + B = (2, 4) + (3, 5). A’s X value = 2, B’s X value = 3. And 2 + 3 = 5. Do
the same with Y and you have: (2+3, 4+5), which is the same as (5, 7) and we have a
combined vector equal to A + B.
You can also add vectors visually. It is very easy indeed. If you want to add the vectors
above on a paper you simply move one of the vectors to the end point of the other. Then
you draw a new vector from A’s start point to B’s end point. Erase A and B and we are left
with the resulting vector C. See the graphical example below. (here I moved B’s start point
to A’s endpoint).
A
B
B
C
A
Note that the direction of the C vector is something in-between the A and B vector.
Let us take another example: Imagine a spaceship, it is affected by gravity which pulls it
down, the only thing that stops the ship from crashing is the force from the thrusters. You
want to get the resulting force on the ship so that we know where/how/if it is
accelerating. To do that you simply take the gravity, G-vector and add it to your thrust, TVector and you have the total force acting on your ship.
T
G
G
D
In the example above the resulting vector is called D. If you look at the D vector you will
notice it is very short and that it points left and up. In other words, the ship will
accelerate along the D vector because it is being affected by two forces (the Trust, and
the Gravity!)
Take a look at this example (copy N paste into Blitzmax).
4
Written by Patrik Strandell - mail: Patrix@Truplo.com
Last Edit:
February 6, 2016
VelocityA:= New Vector
VelocityB:= New Vector
VelocityA.Set( 2, 2 ) 'Down Right
VelocityB.Set( 0,-4 ) 'Up
Print "We have two Vectors:"
VelocityA.Write("A")
VelocityB.Write("B")
Print "Add B to A"
VelocityA.Add( VelocityB )
Print "And A is now:"
VelocityA.Write("A")
Class Vector
Field X,Y
Method Add( Vector:Vector2D )
X:+Vector.X
Y:+Vector.Y
End
Method Set( X, Y)
Self.X = X
Self.Y = Y
End
Method Write( Name$ )
Print "Vector "+Name+" ("+X+", "+Y+" )"
End
End
How to code with vectors?
We want to make practical use of vectors in our game. The best solution would be to use a
vector library (or you will have to make one yourself). I’ll show some code where I will be
using a Vector Library to show you how the end result may look like:
'Taken from the asteriods demo:
If KeyDown( Key_Up )
Thruster = New Vector
Thruster.SetLength( Ship_Acceleration )
Thruster.SetDir( Ship_Direction )
Speed.Add( Thruster )
End
'Add Gravity – Note this is a special case, where Acceleration = Force
Speed.Add( Gravity )
Turning vectors into physics and mechanics
Let’s say you have a fair understanding that a vector has a length and a direction, that it is
used to describe such things as forces, accelerations, positions and velocity. Now it’s time
to put this system together so we can have some real use of them. We are now going to
model (i.e. describe and simulate with code) physics. You must understand that to model
physics we have to make idealizations to approximate the real world and this is no-where
near any exact science. When it comes to game programming, the most important thing is
that the feeling is right. I will start with the theories and end with a huge example.
5
Written by Patrik Strandell - mail: Patrix@Truplo.com
Last Edit:
February 6, 2016
Physics in game programming
Index ------------------------------ Position
 Velocity
 Acceleration
 Forces and inertia
o Gravity and Weight
o Friction
o Wind/Air resistance
o Bounce – elasticity
Position
An objects position can be described as a vector from the world origin to the object itself.
A 2D vector consists of two values, X and Y. A position or point in 2D have the same data,
so what we do is that we use some vectors to describe positions. The top-left corner of
the screen is our origin and is therefore position (0, 0).
We need one position vector for each object we want to draw. To draw your spaceship with
a position vector you could do:
DrawImage( Ship.Image, Ship.Position.X, Ship.Position.Y )
Imagine yourself buying a map of the local area in a store. After having walked away from
the store for a couple of minutes you check your new map. You mark to store and you mark
your position. To determine your position you could draw a line from the store to you. This
is if we use the store as our origin. You can use the North Pole as your origin if you want,
but then you are very likely to get very large numbers. The store being the origin and this
line is you position vector. Every step you take will add to this position vector, and the
position vector will get longer as you get further away to the store. The magnitude or
length of the position vector is the distance away from the store you are, as if you
measured the line, to you from the store, on the map. Also consider that the distance to
the store from you never can get negative, right?
If you have the position vector of two objects A and B and want a vector between A and B.
The result is very easy, it is (A-B) or (B-A). (A-B) is a vector from B to A, while (B-A) is a
vector from A to B. The distance between the objects A and B is the length of this vector.
Velocity and Speed
The velocity of an object determines how fast it travels in a given direction. Velocity is
always described by a vector. Speed on the other hand is the length of this velocity vector
and has nothing to do with the direction, which means speed is not a vector. Velocity is an
objects change in position over time. This is why you always add an objects velocity to its
6
Written by Patrik Strandell - mail: Patrix@Truplo.com
Last Edit:
February 6, 2016
position. For example, when you walk, every step you take alters your position. The faster
you walk the greater is your speed and the faster you change your position. If you start to
turn while still keeping the same speed, your velocity will change (The direction of the
velocity).
Acceleration
Acceleration is the rate at which we change our velocity over time. Like velocity
acceleration is described by a vector. A high acceleration means we gain speed fast. We
add our combined acceleration of an object to its velocity. Note that zero acceleration
does not mean we are not moving, it only means we are not accelerating; changing our
velocity. A spaceship could for example be traveling super fast and still have zero
acceleration.
Forces and inertia
Force is also a vector and has a length and direction. Force creates acceleration depending
on the objects mass. An object’s mass determines how much force is needed to speed it up
or slow it down. In the real world objects that have a greater mass will require more
energy to move (referred to as inertia). The greater the object’s mass, the more force it
takes to change its motion. Imagine two spaceships in space, one big and one small. The only
thing surrounding these spaceships is empty space. They both have the exact same
thrusters and they both initiate it at the same time. What will happen? Answer: The small
ship will accelerate much faster than the big one. This may sound strange because there is
no air (i.e. no air friction), so what is it that limits the acceleration of the big ship? To put
it simple: It’s mass. Both these thrusters develop the same constant force, but this does
not give them the same acceleration.
When we code this means that we never‡ want to change the objects acceleration directly;
we change the force which creates an acceleration (depending on the mass) which in turn
changes our velocity which in turn alters our position. All forces that act upon an object
can easily be added into one total force. Also note that an object with the mass = 1 will
have its acceleration equal its force, which was the case with the asteroids example.
Take a look at this data and calculations of our two ships (this is not a program, just data):
SpaceShipThruster = 50' Force of Thruster
BigShip.Mass = 10
SmallShip.Mass = 5
Loop
BigShip.Force.Add(
SpaceShipThruster)
SmallShip.Force.Add( SpaceShipThruster)
'F = M*A
‡
gives us that A = F/M
Never say never, but in general this is how it works.
7
Written by Patrik Strandell - mail: Patrix@Truplo.com
Last Edit:
February 6, 2016
BigShip.Accel
= Force.Divide( BigShip.Mass )
SmallShip.Accel = Force.Divide( SmallShip.Mass )
EndLoop
TimeStep_1
SmallShip: Force=0 Acceleration=0 Velocity=0 Position=30
BigShip:
Force=0 Acceleration=0 Velocity=0 Position=5
TimeStep_2 'Start Engines!
'This is how the acceleration will be calculated
BigShip.Accel
= 50 / 10 = 5
SmallShip.Accel
= 50 / 5 = 10
BigShip:
Force=50 Acceleration=5 Velocity=5 Position=35 (30+5)
SmallShip: Force=50 Acceleration=10 Velocity=10 Position=15 (5+10)
TimeStep_3
BigShip:
Force=50 Acceleration=10 Velocity=10
SmallShip: Force=50 Acceleration=20 Velocity=20
'Big ship still has the lead
TimeStep_4' Stop Both Engines!
BigShip:
Force=0 Acceleration=0 Velocity=10
SmallShip: Force=0 Acceleration=0 Velocity=20
'They are at equal positions!
Position=45 (35+10)
Position=35 (15+20)
Position=55 (45+10)
Position=55 (35+20)
TimeStep_5' BigShip starts its thruster! (see force)
BigShip:
Force=50 Acceleration=5 Velocity=15 Position=70 (55+15)
SmallShip: Force=0 Acceleration=0 Velocity=20 Position=75 (55+20)
TimeStep_6' BigShip still has it’s thruster going
BigShip:
Force=50 Acceleration=5 Velocity=20
SmallShip: Force=0 Acceleration=0 Velocity=20
Position=90 (70+20)
Position=95 (75+20)
The small ship has a much higher acceleration, and the big ship has a much slower. Their
top speed is totally unaffected. The big ship can come up in the same speed as the small
ships; it just takes it more time which would also result in more fuel. A smart shipbuilder
would therefore give big ships stronger engines for faster acceleration. If this example
would have been about two submarines the situation would be different. For example the
size of the sub would matter much more than its weight as it propels through the water,
yet the mass – thruster relation remains valid.
Weight and Gravity
Weight is not the same as mass. Mass is a value, weight is a force. Weight is not just any
force; it is a special case that only exists when a large gravitational field is involved. This
could for example be the surface and atmosphere of any planet. In our everyday life we
can’t get away for the concept of weight. If you for example take six kilograms of apples
to the moon they would weight only one kilogram. The apples would still consist of the same
amount of molecules so their mass would be the same, yet the gravitational force which
pulls them down towards the scale would be less. To mimic weight we simply add a constant
downward force to each and every object. Gravity comes from mass and if you are doing a
game where you travel between planets you might want to read some more on the subject.
Sum up: Gravity creates a force, the force creates acceleration. Faster acceleration on
8
Written by Patrik Strandell - mail: Patrix@Truplo.com
Last Edit:
February 6, 2016
objects with small mass and slower acceleration with objects that has a big mass. The
acceleration increases the objects velocity. The velocity makes the object move and also
increased the objects movement energy which in turn would lead to a greater impact if it
collides.
Friction
Friction is a force which appears when two surfaces touch or when an objects moves
through a gas or liquid. First I will separate fluid friction from surface friction, we will
model (i.e. code) them differently.
Friction Surface against Surface
The friction is always acting opposite to the movement of the object. You can say that the
friction force is breaking the force trying to move the object. A very important factor is
the material of the object. Actually it’s the roughness
of the surface that matters§; they usually go hand in
hand. Even the smoothest material becomes jaggy as
you enlarge it. See picture. We also need to consider
how hard the object is pressed against the surface. On
earth this would mean an object of greater mass would
take more force to push on a floor than a lighter object,
because objects of larger mass have a large weight,
pushing it down into the floor; creating a greater friction than the lighter object.
With a vector library you could code friction like this:
Speed.Decrease( Friction )
Wind/Air resistance
This friction is dependant on the objects speed. The higher the speed, the higher is the
reversed force from the air resistance. At one point the force, from our thruster that
accelerates us, will be equal to the friction holding us back; our maximum velocity. If you
drop a feather and a hammer they will accelerate at the same speed towards the ground.
Without air resistance they would also hit the ground at the exact same time **. Those who
do not know physics usually miss this point. All objects are affected by the same constant
gravity acceleration, no matter their mass.
You may ask yourself “Does not mass have any affect on gravity?” or “How can the mass of
the object be irrelevant”?
The acceleration from gravity for every object on earth is ~9.8m/s2 downwards. This
means that more mass equals stronger gravitational force. A heavier object will have a
§
**
Exception: extremely smooth materials may “cold weld”.
This was tested on the moon, which has no air – they did hit the ground at the same time.
9
Written by Patrik Strandell - mail: Patrix@Truplo.com
Last Edit:
February 6, 2016
stronger pull downwards. But it will not accelerate faster. Because if you think back to our
spaceships, the more mass the bigger force is required to move the object! They cancel out
each other:
MilkboxMass = 1'Kg
CarMass = 700'Kg
Print "MilkboxMass: "+MilkboxMass
Print "CarMass: " +CarMass
M
M
'F = m*a The formula, Force equal Mass times Acceleration
GravityAcceleration# = 9.8'on Earth!
Print "Gravity on Earth = "+GravityAcceleration
'
F
=
M
*
A
(Force is Mass multiplied by acceleration)
MilkboxForce = MilkboxMass*GravityAcceleration
CarForce = CarMass*GravityAcceleration
Print "MilkboxForce: "+MilkboxForce
Print "CarForce : "+CarForce
'Force = Mass*Acc <-- is the same as --> Acc = Force/Mass
MilkboxAcceleration = MilkboxForce / MilkboxMass
CarAcceleration = CarForce / CarMass
Print "Milkbox Acceleration: "+MilkboxAcceleration
Print "Car Acceleration: "+CarAcceleration
The difference in acceleration between a feather and a hammer is their air resistance and
nothing else, which is much higher for a feather and is indeed very dependant on weight
and size.
Momentum
Momentum is a measurement of an objects ability to resist change in velocity. The greater
the speed and the larger the mass, the greater will the object’s momentum be. Momentum
is a vector quantity and always has the same direction as the objects velocity vector.
There will be times where objects of different mass and different speeds collide. Some
times you might even have an object that increases or decreases its mass. That could for
example be a helicopter landing on a train, where as the trains mass gets a little bigger,
and therefore the train’s velocity will decreases slightly.
The total momentum of all objects in a system always stays the same, momentum cannot be
lost; it can only be transferred. Take two cars for example: One traveling at 70km/h and
another at -150km/h, both cars have the same mass 700kg. The cars are heading against
each other. If they collide they will smash together into a piece of metal. Let’s calculate
the speed they will have after impact by using their momentum. Car1’s momentum is
70x700=49 000. Car2’s momentum is -150x700 = -105 000. Add the momentum: -105k +
49k = -56k. We now have the total momentum before the crash. Divide by the total mass
of the metal junk pile 700*2. -56k/1.4k = -40km/h. We get the resulting velocity for both
objects with the assumption they will stick together. The negative sign only indicates the
10
Written by Patrik Strandell - mail: Patrix@Truplo.com
Last Edit:
February 6, 2016
direction because this was a 1D example. Also I use SI units, mass in kilograms, speed in
kilometers/hour.
Elasticity
I assume you have noticed that different objects and materials have different bounciness.
If you drop a sandwich on the floor it is not expected to bounce up compared to if you drop
an empty can of soda. When the object hit the ground some of the energy the objects has
in form of motion is converted to heat. The elasticity of the object determines the amount
converted. The energy that does not become heat will keep the object moving and make the
object bounce back from the surface. If no energy would be lost in the hit, the object
would keep the same speed after the hit, objects like that are said to be elastic.
Simple Gravity Bounce Example
'Gravity
'Put this part in an OnEnter State, or OnCreate
BallX! = 150, BallY! = 20'Start Top Middle
Size = 50
Elasticy# = 0.9 'From 0.0 to 1.0 where 0.9 = bouncy, 0.1 = sticky
Gravity# = 0.05 'Constant Gravity
'Put this part in OnExecute or OnUpdate
BallYVel:+ Gravity
DrawOval BallX,BallY,Size ,Size
'Collision with elasticity
If BallY => DeviceHeight()-Size And BallYVel > 0
BallYVel = -BallYVel*Elasticy
BallY = DeviceHeight()-Size
EndIf
BallY:+BallYVel
Tech-Demo
Here follow a tech-demo of some simple vector physics. This shows what you can do with
vectors. Run the demo before you look at the code. Try to tweak it; change gravity, friction
and such. Note: This example is more for testing than learning.
' Have a ball that is affected by gravity and bounces against the sides of the screen
' Make the ball apply an acceleration towards your mouse
Class Vector
Field X#,Y#
Function Create:Vector( X#=0, Y#=0 )
Local NewVector:Vector = New Vector
NewVector.X = X
NewVector.Y = Y
Return NewVector
End
Method Add( OtherVector:Vector ) X:+ OtherVector.X ; Y:+ OtherVector.Y End
Method Multiply( Value# ) X:*Value; Y:*Value
End
Method Visulize( Start:Vector , Multiply# = 20 , Xtra = 0)
11
Written by Patrik Strandell - mail: Patrix@Truplo.com
Last Edit:
February 6, 2016
DrawLine Start.X + Xtra, Start.Y, Start.X + Xtra + X* Multiply , Start.Y + Y*
Multiply
End
'
'
'
Method Draw( Start:Vector )
DrawLine Start.X, Start.Y, Start.X + X , Start.Y + Y
EndMethod
Method ReverseX()
X = -X End
Method ReverseY()
Y = -Y End
Method Set( X#=0, Y#=0) Self.X = X;Self.Y = Y
End
Method Length#()
Return Sqr( X*X + Y*Y )'Pythagoras
End
Method VectorFrom( Position1:Vector , Position2:Vector)
X = ( Position2.X - Position1.X )
Y = ( Position2.Y - Position1.Y )
End
'Decrease a vector until it is zero
Method Break( Amount# )
If Amount = 0 Return'We don't brake..
If Amount >= Length(); Self.Set(0,0) Return'No matter how much you brake you'll
never go backwards
Local Break:vector = Vector.Create( X / Length() , Y / Length() )
Break.Multiply( -Amount# )
Self.Add( Break )
End
End
Type TBounceBall
Field
Field
Field
Field
Field
Field
Field
TopLeft:Vector
'Not in use, I think
Position:Vector
Velocity:Vector
'I hope these are self-explainatory
Acceleration:Vector
Force:Vector
Mass#
Radius 'Size of ball
Method New()
TopLeft
Position
Velocity
Acceleration
Force
Radius
Mass
End
=
=
=
=
=
=
=
Vector.Create( 0 , 0)
Vector.Create( 50, 250)
Vector.Create( 0 , 0)
Vector.Create()
Vector.Create()
30
1
Method Draw( )
DrawOval( Position.X - Radius/2, Position.Y - Radius/2, Radius, Radius )
'Draws a oval around the ball's position
'If I wouldn't take X - radius/2 the oval would be draw from the middle.. Try it
End
Method Update()
Force.Multiply( Float(1.0/Mass) )
Acceleration.Add( Force )' a = F/m
Velocity.Add( Acceleration )
Position.Add( Velocity )
; F =
12
m*a ; m = F/a
Written by Patrik Strandell - mail: Patrix@Truplo.com
Last Edit:
February 6, 2016
' D I S P L A Y
V E C T O R S
'----------------------------------------------------'Draw and magnify the vectors so we can see them
'_____________________________________________________
SetColor 0,255,0
DrawText "GREEN Vector is the Velocity Vector"+Velocity.Length(),10,80
Velocity.Visulize( Position ,4 )
SetColor 255,0,0
DrawText "RED Line is the Acceleration Vector. Lenght:
"+Acceleration.Length(),10,50
Acceleration.Visulize( Position ,50, -1)
'_____________________________________________________
SetColor 255,255,255
Force.Set
Acceleration.Set
'Velocity.Set
End
Method CollideWalls()
If Position.X < 0' And Velocity.X > 0'Left
CollideVerticalWall( 0 )
Else If Position.X > GraphicsWidth()' And Velocity.X < 0'Right
CollideVerticalWall( GraphicsWidth() )
Else If Position.Y < 0' And Velocity.Y > 0'Top
CollideHorisontalWall( 0 )
Else If Position.Y > GraphicsHeight() 'And Velocity.Y < 0'Bottom
CollideHorisontalWall( GraphicsHeight() )
EndIf
End
Method CollideVerticalWall( WallX )
Velocity.ReverseX()
Velocity.Multiply(0.8)' Fotball bounce - 1 for super bounce, 0 for no bounce
Acceleration.ReverseX()
Local DistanceIntoWall = (Position.X - WallX)
Position.X:- 2*DistanceIntoWall
End
Method CollideHorisontalWall( WallY )
Velocity.ReverseY()
Velocity.Multiply(0.8)' Fotball bounce - 1 for super bounce, 0 for no bounce
Acceleration.ReverseY()
Position.Y:- 2*(Position.Y - WallY) ' (Position.Y - WallY) = DistanceIntoWall
End
End
Local
Local
Local
Local
Ball:TBounceBall = New
MousePosition:Vector =
MouseForce:Vector
=
GravityAcc:Vector
=
TBounceBall
Vector.Create( MouseX(), MouseY() )
Vector.Create()
Vector.Create( 0 , 0.2 ) 'Constant Acceleration Downwards
Local Gravity = False 'Activate with [ G ] key
Local Friction = False 'Toggle Friction [ F ] Key
Graphics 500,500,0 'Window debug Mode
While Not KeyDown(Key_Escape)
13
Written by Patrik Strandell - mail: Patrix@Truplo.com
Last Edit:
February 6, 2016
MousePosition.Set MouseX() , MouseY()
MouseForce.VectorFrom( Ball.Position, MousePosition )
MouseForce.Multiply( 0.01 )'0.1%
If
If
If
If
KeyDown(
KeyDown(
KeyDown(
KeyDown(
Key_MouseLeft ) Ball.Force.Add( MouseForce )
Key_X ) Ball.Force.X = 2
Key_A ) Ball.Velocity.X = 2
Key_Z ) Ball.Acceleration.X = 2
If KeyHit( Key_G )
If Gravity = False Then Gravity = True Else Gravity = False
End
If Gravity
Ball.Acceleration.Add( GravityAcc )
'We only have one object
'In a normal case you would loop this for every object affected by gravity
'NOTE: Gravity is an accleration; independant of Mass - it is not a force!
End
If KeyHit( Key_F )
If Friction = False Then Friction= True Else Friction = False
End
If Friction'Apply Friction unless SPACE is hold down
Ball.Velocity.Break( 0.1 )'FRICTION
'This is not very good air friction, but should work
'good for pool balls or rolling minigolf balls.
End
Ball.Draw
' Draw Ball
SetColor 0,0,255
DrawText "All BLUE Lines is Force Vectors",10,20
SetColor 0,100,255
MouseForce.Visulize( Ball.Position, 10 )
SetColor 25,25,155
Ball.Force.Visulize( Ball.Position, 10 )
Ball.Update
' Update the balls velocity, acceleration and position
Ball.CollideWalls
DrawText "Press G to Toggle Gravity ON/OFF",10,150
DrawText "Press F to Toggle Friction ON/OFF",10,180
DrawText "Press LeftMouse to draw the ball toward the cursor",10,210
Wend
14
Written by Patrik Strandell - mail: Patrix@Truplo.com
Last Edit:
February 6, 2016
Appendix!
The formula for the Force – Acceleration relation is like this: F = mA
F = Force - Vector
A = Acceleration - Vector
m = Mass – Scalar (normal value)
Formula Surface Friction: F = µ N
F = Friction Force - Vector
µ = Surface Roughness, depends on the material involved, see the table below - Scalar
N = Total Force pulling the object towards the surface – Scalar
Formula for relation between position, time and speed, d = Vt
d = Distance – Position Vector
V = Velocity - Vector
t = time -Scalar
Formula for calculating the length of a vector – Pythagoras statement,
C2 = A2 + B2  which is the same as  C = Sqr(AxA + BxB)
C = length - Scalar
A = X field of vector - Scalar
B = Y field of vector – Scalar
Formula for Momentum, P = mV
P = Momentum – Vector
m = Mass – Scalar
V = Velocity - Vector
The total moment of a system is always conserved.
Elastic collisions considering Momentum
When two objects collide, their velocities will change. Here is a formula to calculate the
new velocity:
V1after = (m1-em2)V1 + (1+e)m2V2 / ( m1 + m2 )
V2after = (m2-em1)V2 + (1+e)m1V1 / ( m1 + m2 )
V1 = Velocity of object 1, before collision.
V2 = Velocity of object 2, before collision.
m2= Mass of object 2.
m1= Mass of object 1.
e = Coefficient of Restitution, determines energy lost in collision.
e is a percentage value from 0 to 1. 1 = perfect bounce, 0 = no bounce (mud).
V1after = Velocity of object 1, after collision.
V2after = Velocity of object 2, after collision.
X = means multiplication – Math symbol, also know as *
15
Download