Omnimaga

Calculator Community => TI Calculators => Axe => Topic started by: Builderboy on March 13, 2010, 10:58:33 pm

Title: Physics Lessons
Post by: Builderboy on March 13, 2010, 10:58:33 pm
GRAVITY:

One of the most basic Physics concepts that you might want to implement in a game is gravity.  Whether it be in a platformer, a pinball game, or something else, gravity is a common need.  So to start off, we need to ask ourselves, what it gravity?  Gravity acts on all objects on earth, and pulls the objects towards the surface, we all know that.  But its not merely as simple as decreasing the players position by 1 each frame, things don't fall that way*, as they fall they get faster and faster.  This phenomenom is known as acceleration and is the concept behind gravity and all accelerating physics.

Acceleration is measured in X Meters per second per second.  That is to say, every second, your velocity will increase by X Meters per second.  Since we live in the game world, it would be more somthing like X pixels per frame per frame.  That is to say, every frame, your velocity will increase by X pixels per frame.  Lets say your position starts at 0 and your velocity starts at -3 and you are in an empty world with 1 P/F/F
acceleration (1 pixels per frame per frame).  This chart shows your position, velocity, and acceleration for a few frames

Code: [Select]
Frame Position Velocity Acceleration
0 0 -3 1
1 -3 -2 1
2 -5 -1 1
3 -6 0 1
4 -6 1 1
5 -5 2 1
6 -3 3 1
7 0 4 1
8 4 5 1
9 9 6 1
10 15 7 1

The code for this would look something like

Code: [Select]
0->X
-3->V
1->A

While 1
Output(1,1,X)
X+V->X
V+A->V
End

Notice that even when the velocity is positive, the position can still be negative, and vica versa.  But you can see that the position starts off moving downwards, stops at -6, then starts moving upwards again.  Acceleration stays constant througout the entire simulation.  If you want to get really technical, you can go into how velocity is the derivative of position blah blah blah, but you dont need to know that in a game ;)

HOW TO USE IT:

Implementing acceleration is simple, especialy if your acceleration is constant.  You only need a single variable for your position and one for your velocity.  If you want changing acceleration you could add a variable for that too.

Also note that X velocity is INDEPENDANT of Y velocity.  That is to say, if your character has a velocity in the X direction, and has gravity affecting it, since gravity is only in the Y direction (unless your game is uber cool) the Y acceleration will only affect the Y velocity will only affect the Y position.  Try this example program for size:

Code: [Select]
ZStandard
ZInteger
AxesOff
Clrdraw
0->X
0->Z
0->A
0->B

While 1
PtOff(X,Z,2
X+A->X
Z+B->Z
PtOn(X,Z,2
getKey->K
A+(K=26)-(K=24)->A
B+(K=25)-(K=34)->B
End

Its a fun example of the power of acceleration, see if you can add gravity to it!  You might have some interesting results.

WHAT TO WATCH OUT FOR:

Acceleration is not always applied, for example when you are standing on a platform, both your velocity and your acceleration are 0.  More on this will be covered in the next section 'Collisions'
Title: Re: Physics Lessons
Post by: _player1537 on March 13, 2010, 11:05:52 pm
Builderboy,  thank you.  I look forward to the next section  ;D
Title: Re: Physics Lessons
Post by: Radical Pi on March 13, 2010, 11:18:39 pm
Good tutorial! I can't wait for what you have to say on collisions with acceleration; I've always wondered how to prevent accelerating through something.
Title: Re: Physics Lessons
Post by: trevmeister66 on March 13, 2010, 11:25:43 pm
Wow, that is amazing. *trevmeister66 starts messing around with his new found knowledge
Title: Re: Physics Lessons
Post by: {AP} on March 13, 2010, 11:27:25 pm
All this does is remind me of how I never paid enough attention in Physics class. xP
Nice to see my wasted education in code form though. I sometimes have a hard time taking real life concepts and converting them to code effectively.
Title: Re: Physics Lessons
Post by: DJ Omnimaga on March 13, 2010, 11:29:56 pm
This is interesting. It might be more suitable in animations or very simple games, though, since extreme gravity calculations can take a while in TI-BASIC. Otherwise, maybe Axe Parser. Maybe it could also help other kind of programmers too. Maybe it could help for a Sonic game too :P (since the one on UTI seems to never be going anywhere...)
Title: Re: Physics Lessons
Post by: meishe91 on March 14, 2010, 12:40:13 am
Thanks, that is pretty sweet. I'm gonna have to go over it more though since I still don't quite understand. What would you even use though for your gravity acceleration? I mean gravity in real life is 9.81... m/s2 (and 32... ft/s2 but I don't think that would work very well on the graph/home screen. But I don't know.
Title: Re: Physics Lessons
Post by: Builderboy on March 14, 2010, 12:56:00 am
I sometimes have a hard time taking real life concepts and converting them to code effectively.
Yeah that can be a very hard challenge.  Especially when talking about really complicated things like rebound angles and the like D:

This is interesting. It might be more suitable in animations or very simple games, though, since extreme gravity calculations can take a while in TI-BASIC. Otherwise, maybe Axe Parser. Maybe it could also help other kind of programmers too. Maybe it could help for a Sonic game too :P (since the one on UTI seems to never be going anywhere...)
Yeah, one thing thats hard about implementing physics well is that it often times takes a lot of processing time.

What would you even use though for your gravity acceleration? I mean gravity in real life is 9.81... m/s2 (and 32... ft/s2 but I don't think that would work very well on the graph/home screen. But I don't know.
Well in Portal i believe i used 1/64 pxl per frame per frame, but it depends heavily on your frame-rate.  The best way to find a good acceleration is just to run some tests.  As a general rule you don't want your player moving too fast because that makes collision very difficult.
Title: Re: Physics Lessons
Post by: meishe91 on March 14, 2010, 01:07:09 am
Hmmm, ok. That makes sense. Thanks.
Title: Re: Physics Lessons
Post by: AaroneusTheGreat on March 14, 2010, 03:12:52 am
Quote
Well in Portal i believe i used 1/64 pxl per frame per frame, but it depends heavily on your frame-rate.  The best way to find a good acceleration is just to run some tests.  As a general rule you don't want your player moving too fast because that makes collision very difficult.

Sometimes you can get around the collision detection issue with fast motion by pre-calculating the next position, and calculate where it would actually collide if it were going point by point, then simply change the position of the object to that collision point, thereby bypassing any graphical glitches you might have in your detection. It can be a pretty simple section of code within your collision detection subroutine.

What I would really like to know is how you solved the problem of implementing angular momentum in addition to gravity when you come out of a portal from another direction. I was having a time trying to figure that out.

EDIT:

I read back over some of the tutorial, it says you're doing a section on collision detection, I'm interested to see what methods you have to implement this and what kind of uses you're going to cover. It can be a really tricky thing, especially in an environment like Portal, any 3D environment, or any environment involving uneven surfaces or curved objects. I'm sure you've got a few tricks up your sleeve from what I've seen you do so far. :D
Title: Re: Physics Lessons
Post by: DJ Omnimaga on March 14, 2010, 03:29:49 am
As a general rule you don't want your player moving too fast because that makes collision very difficult.
True, else stuff like this (http://www.youtube.com/watch?v=tx061196cvI) happens :P
Title: Re: Physics Lessons
Post by: Galandros on March 14, 2010, 10:02:03 am
Very nice topic.  ;)

Really easy to follow and learn. Collision is a must for next update. :P
Title: Re: Physics Lessons
Post by: ztrumpet on March 14, 2010, 11:17:16 am
That's really awesome Builderboy!  Thanks, and I can't wait for collisions!   
 *ZTrumpet thinks about making some sort of physics game with Axe with this new knowledge... ;D
Title: Re: Physics Lessons
Post by: jsj795 on March 14, 2010, 11:19:55 am
One of my first games actually involved the gravity, like the helicopter... But it was super slow, and I think it could've been a lot faster if I used Builderboy's code!

You taught me that Physics class can definitely be applied in some area :)
Title: Re: Physics Lessons
Post by: DJ Omnimaga on March 14, 2010, 08:23:01 pm
btw, since there are people who are visual, it might be a good idea to have some eye candy of the examples in action. Just a suggestion for the tutorial
Title: Re: Physics Lessons
Post by: meishe91 on March 28, 2010, 05:20:46 am
Hey Builderboy, how is the next section of this looking? Just curious because I can't wait to learn more ;D
Title: Re: Physics Lessons
Post by: SirCmpwn on March 28, 2010, 12:11:28 pm
Builderboy, amazing tutorial.
I would like to suggest however that this be discussed more in the frame of inertia, because applying inertia takes care of this and allows for other movements beyond gravity to be more accurately portrayed.
Title: Re: Physics Lessons
Post by: DJ Omnimaga on March 28, 2010, 12:40:03 pm
maybe also explain to non visual people special vocabulary used in the tutorial for physics. I notice that when I read a tutorial, if I have to go on Wikipedia/Google every sentence, it gets annoying and I eventually lose interest because I can't stay into the tutorial.
Title: Re: Physics Lessons
Post by: ztrumpet on April 02, 2010, 01:11:37 pm
*Bump*

Builderboy, when's the next section of this coming?
I know I, for one, am really looking forward to it! ;D
Title: Re: Physics Lessons
Post by: Raylin on April 02, 2010, 01:30:03 pm
^++
Agreed and seconded.
Title: Re: Physics Lessons
Post by: Builderboy on April 02, 2010, 06:20:31 pm
Its coming soon-ish.  School has suddenly gone into overdrive with teachers starting to prepare for AP testing, so its been pretty hectic X.X Collision is being worked on tho, as well as an update to gravity :)
Title: Re: Physics Lessons
Post by: DJ Omnimaga on April 02, 2010, 07:35:00 pm
I hope they won't overload you even more with projects x.x, it would suck if you had to stop working on this. Good luck on everything!
Title: Re: Physics Lessons
Post by: meishe91 on April 02, 2010, 08:47:30 pm
Ya, I know what you mean about the AP test prep time. Glad to hear its coming though.
Title: Re: Physics Lessons
Post by: Builderboy on April 07, 2010, 01:23:39 am
OK here is a quick (kinda) lesson on trig and the wonders of Triangles!  Unplanned, so its coming before collisions :P

************
Trigonometry    NOTE: put your calc in degrees mode!
************

Trig is one of those things that can be very usefull in games, but is actualy fairly
difficult to figure out without some good instruction.  That is where this tutorial
is going to try to help.  

trigonometry is the mathematics of trianlges.  Take this triangle for instance

Code: [Select]
      |\
      | \
  a   |  \ C    (hypotenuse)
(leg) |   \
      |    \
      +-----
         b (leg)

It is a right triangle because the angle between side A and side B is 90 degrees.  This is
the only type of trignale we will discuss in this tutorial, and usualy it is the only one you
will need.

In addition to having 3 sides, there are also 3 angles. AB, AC, and BC.  You can also call them
by the sides that are *opposite* to that angle, so angle AB would be angle C.  We already
established that angle AB is 90 degrees.  This triangle is a RIGHT triangle, because it has one
right (90 degree) angle, and Right Triangles are your friend :)

For starters, here is the pythagorean theorem:

A^2 + B^2 = C^2

Hmmm interesting, for all Right Trignales, the sum of each leg squared, equals the hypotenuse squared.
(remember, the legs are the two sides that make the right angle)  What this means for us is that
for any right triangle, if we are given 2 sides, we can find the other with this equation.  This
is a way to calculate the distance to a point, as you can use the 2 legs as the X and Y distances
to a point.

Code: [Select]
              B
              /|
    / |    The distance from A to B is the hypotenuse of a right triangle, with X and Y
   /  |    as the legs.
  /   | Y
 /    |    Distance^2 = X^2 + Y^2     Take the square root, and we have:
/     |
A------+    Distance = SQRT(X^2 + Y^2)
            X

Now, we have worked with the sides, what about the angles?  The angles between two sides is the ammount
of rotation between them:

Code: [Select]
 |
  |          \                         /
  |           \                       /
  |            \                     /
  | 90 degrees  \   135 degrees     /  45 degrees
  |              \                 /
  +---------      --------        ---------

Somtimes we want to rotate a sprite or an object around a point.  Like this:

Code: [Select]
ZStandard
ZInteger
AxesOff
ClrDraw
For(F,0,360,5
Pt-On(29cos(F),29sin(F
End

What??? How did i just do that? Well the answer lies in trig, and in right triangles.  You may not think
that triangles have much to do with circles, but in fact, they have everything to do with eachother.
A circle contains all the points a certain radius from a center point.  So given a radius, there are
different X,Y points that lie onto a circle.  Does this look farmiliar?  Look again at the distance formula:

Distance = SQRT(X^2 + Y^2)

If we say that Distance is the radius, this distance equation becomes the equation of a circle!  :O
It gives us an euqation, where if we have a radius (distance) and an X or Y value, we can find the
other coordinate.  

Try solving the distance equation for Y

Distance = SQRT(X^2 + Y^2)
Distance^2 = X^2 + Y^2
Distance^2 - X^2 = Y^2
SQRT(Distance^2 - X^2) = Y

Y = SQRT(Distance^2 - X^2)

Try putting this into Y1 in your calculator, set Distance to 5 lets say, and graph it!  You get a circle!
(or half of one anyway... stupid functions...)

Wow, thats really cool, we can get a circle without doing any trig at all!



Now comes the final challenge, using the above equation, we can find all of the points on a circle, given
the radius, but what if we want a singe point?  We already have the radius, but we do not have any other

variables
to determine which point to use.  We need another, and that is the angle.  A circle goes accross 360 degrees
or angle, starting at the rightmost point at 0 degrees and rotating accross the circle counterclockwise until
it gets to 360 degrees, where it started.

Now it is time to introduce Sin, Cos, and Tan.  These functions pertain to triangles and their angles, and are
all very usefull.  For right triangles, you only take the sin, cos, or tan of angles that are NOT the Right

Angle
So for this triable they would be AC and BC

Code: [Select]
      |\ Sin of an angle equals the opposite leg over the hypotenuse
      | \ Sin(BC) = A/C Sin(AC) = B/C
  a   |  \ C    (hypotenuse) Cos of an angle equals the adjecent leg over the hypotenuse
(leg) |   \ Cos(BC) = B/C Sin(AC) = A/C
      |    \ Tan of an angle equals the opposite over the adjecent
      +----- Tan(BC) = A/B Tan(AC) = B/A
         b (leg)

These trigonometric equations give us some interesting power.  If we know Hypotenuse C and Angle BC,
we can find leg A.

Sin(BC) = A/C
Sin(BC)*C = A
A = Sin(BC)*C

And we can also find leg B as well

Cos(BC) = B/C
Cos(BC)*C = B
B = Cos(BC)*C

Do you know what this meants?  Given a distance, and an angle, we can find the coordinates of that point!

Code: [Select]
              B
              /|
    / |  
   /  |    
  /   | Y
 /    |  
/     |
A------+    
            X

Given the angle at A, and the distance AB, we can calculate the distances X and Y, which are the coordinates of
Point B.

X = R*Cos(A)
Y = R*Sin(B)

its that simple!  And for all angles, point B will be a distance of R form the center, which is the
*exact* definition of a circle!  Given an angle and a radius, using these two equations we can find a
specific point on a circle.

This program shows how the triangles fit into the circle as it travels around the circle:

Code: [Select]
ZStandard
ZInteger
AxesOff
ClrDraw
Degree
0->F

Circle(0,0,30
While 1
Line(0,0,A,B,0 //hypotenuse
Line(0,0,A,0,0 //right leg
Line(A,0,A,B,0  //left leg
29Cos(F)->A //find the coordinates of the next point on the circle
29Sin(F)->B
Line(0,0,A,B
Line(0,0,A,0
Line(A,0,A,B
F+5->F
End
Title: Re: Physics Lessons
Post by: DJ Omnimaga on April 07, 2010, 02:56:08 am
nice tutorial, I didn't read it all, but I am getting some of it atm. Thanks for posting this. I haven't done trig in 8 years now and we only did it for a week at most x.x at school But I ddint take the hardest math classes, so...

Title: Re: Physics Lessons
Post by: meishe91 on April 07, 2010, 03:26:21 am
Very nice. I'll probably read it again tomorrow since it's so late right now but it's good.
I would like to point out to everybody though that your calculator must be set in Degrees mode, not Radians, to follow this. You can follow it in Radians if you know the proper conversions but that's just more work than you need to do :P
Title: Re: Physics Lessons
Post by: SirCmpwn on April 07, 2010, 10:17:37 am
Great tutorial!  I uploaded a gif or your basic demo:
Title: Re: Physics Lessons
Post by: DJ Omnimaga on April 07, 2010, 10:50:03 am
Nice. It appears to erase parts of the circle, though, so you might want to store it in a pic and recall it every frame. Also, instead of Circle(X,Y,radius do Circle(X,Y,radius,{i where i is the imaginary i, not the lowercase ALPHA i. This will be slightly less accurate, but be 3 times faster
Title: Re: Physics Lessons
Post by: SirCmpwn on April 07, 2010, 11:28:28 am
^Explain.  What is the whole {i thing?  And also, for the purposes of a tech demo, I think the parts of the circle can probably stay erased.
Title: Re: Physics Lessons
Post by: DJ Omnimaga on April 07, 2010, 11:50:25 am
i

EDIT: oops accidentally hit a button or something x.x

There we go http://tibasicdev.wikidot.com/circle

It's basically fast circles. Before this was discovered in 2006 people relied on ASM libs to display those.
Title: Re: Physics Lessons
Post by: SirCmpwn on April 07, 2010, 11:56:50 am
Woah, this is cool!  I guess now is as good a time as any to learn this.
Title: Re: Physics Lessons
Post by: DJ Omnimaga on April 07, 2010, 12:09:18 pm
I actually wonder why didn't TI implement those (as well as Text(-1 big fonts) in a more user-friendly way and documented those tricks. I mean, it's not like any harm could have been caused if everyone had access to those functions, plus if anyone would pull off the argument about how with {i circles aren,t as accurate I would say it shouldn't really matter much considering how blocky the calc LCD is in the first place

I wouldn,t be surprised if TI-BASIC hidden more secrets than this. To find all of them, someone would need to disassemble the OS and scout all its code for potential BASIC tricks (or glitches).
Title: Re: Physics Lessons
Post by: nemo on May 15, 2010, 11:47:56 pm
please post the collision detection installment ASAP! i've been messing around with this (getting points to jump, then text, then text sprites.. etc.) but i can't figure out for the life of me how to use pxl-Test( to get a pixel to jump onto a higher platform.
Title: Re: Physics Lessons
Post by: meishe91 on May 16, 2010, 03:06:15 am
Please be patient. I'm sure Builderboy will get to this when he has time. I'm fairly sure he has had school stuff lately (such as AP tests I believe) and other things. Just keep experimenting in the mean time.

An idea though is to have it test the pixel 2 pixels below the character. I can elaborate on that, maybe, if you want.
Title: Re: Physics Lessons
Post by: nemo on May 16, 2010, 12:59:49 pm
sorry if i seemed impatient, i'm just really excited to do something with jumping because when i started programming i couldn't figure out how to (without using a billion if-thens and goto/lbls). Take your time builderboy, i'm only excited.
Title: Re: Physics Lessons
Post by: meishe91 on May 16, 2010, 02:40:45 pm
It's ok, I understand what ya mean. It just seemed to come off as a little rude is all. But like I said just keep experimenting. One thing you can do is ask for help from people here. Like make code that works and then ask for optimization help. We like helping people when we can :)
Title: Re: Physics Lessons
Post by: Builderboy on May 16, 2010, 04:08:07 pm
Yeah I am working on this lesson, but I have been busy for the past few weeks with AP testing so progress has been slow.  That and this lesson is very long ;D Collision is a big topic.  But it is being worked on! Along with Portal and other projects ;)
Title: Re: Physics Lessons
Post by: meishe91 on May 16, 2010, 04:12:54 pm
Other projects? Now I'm really interested :P How'd the testing go? And glad to hear the lesson is being worked on :)
Title: Re: Physics Lessons
Post by: Builderboy on May 16, 2010, 04:23:00 pm
Well my small font editor is kinda slowly slowly getting off the ground, mostly its Just Portal and Zedd, which i need to start up again soon and get a beta released.
Title: Re: Physics Lessons
Post by: meishe91 on May 16, 2010, 04:27:56 pm
Ah ok, what is Zedd?
Title: Re: Physics Lessons
Post by: Builderboy on May 16, 2010, 04:34:51 pm
http://ourl.ca/4665

:)
Title: Re: Physics Lessons
Post by: meishe91 on May 16, 2010, 04:48:59 pm
Oh ya! I completely forgot about that :P How is that going?
Title: Re: Physics Lessons
Post by: Builderboy on May 16, 2010, 04:53:25 pm
Great :) Actualy.  Its being worked on, just like evrything else, although right now Portal has the highest priority.  Haha im partitioning my time :P
Title: Re: Physics Lessons
Post by: meishe91 on May 16, 2010, 05:07:00 pm
Well I'm glad to hear work is going great then :)
Title: Re: Physics Lessons
Post by: ztrumpet on May 16, 2010, 05:10:32 pm
Well I'm glad to hear work is going great then :)
Me too.  I really like all of your projects, and I can't wait for more progress on them all. ;D
Title: Re: Physics Lessons
Post by: DJ Omnimaga on May 16, 2010, 10:08:56 pm
A text display lib using custom fonts in Axe would be cool

Nice to hear this is still alive btw :)
Title: Re: Physics Lessons
Post by: Builderboy on January 31, 2011, 09:28:57 pm
Cellular Automata

Cellular Automata is described by a grid of pixels, where each pixel has a certain amount of rules determining what happens to it.  The Game Of Life is a great example of this type of simulation, but how can this be used for physics?  Using pixel based rules is a great way to simulate large scale effects that would normally be difficult to program.  Things like fluid dynamics, sand, fire, and acid, sounds complicated?  Well all of these things are possible with cellular automata, and will be covered in this tutorial on how to use pixel rules to simulate all of your effects needs.

We are going to base our tutorial off of the water simulation, since that is a simulation that will cover the basics of everything else to come.  Water sounds like an extremely difficult thing to implement on a calculator; it’s so dynamic and hard to define!  How would you even go about storing the data?  Well cellular automata provides a great method for us to solve this.  First, we need to come up with our expectations:

1) The water must be affected by gravity
2) Water must flow


Now that we have our expectations, we need to find some rules that we can apply to our pixels.  In our simulation, each pixel will represent a small part of water, and each pixel will move corresponding to our rules.  I would like to introduce a 3rd rule:

3) Pixels cannot intersect eachother!

This is very important!  If one pixel moves itself onto another pixel, those pixels merge and become a single pixel, and we will lose a small piece of water.  This is fine if that’s what you want, but we want our water to stay at a constant volume, we don’t want to lose any pieces of water.  So no matter what, if a pixel moves, it must always move to an empty space!

With this, we can devise some simple rules:

Code: [Select]
Rule # Condition Action
1 Space below empty Move down
2 Spaces to the sides empty Move either left or right
3 Single empty space to a side Move into that empty space

These rules are followed top to bottom.  This means that first rule 1 is checked, if the condition is satisfied, we do the action.  If not, we move onto the next rule and continue.  If no conditions are satisfied, the pixel stays where it is and we move onto the next pixel.

That’s it!  Those are the rules!  Simple rules right? And yet they can yield surprisingly advanced responses…

(http://www.omnimaga.org/index.php?action=dlattach;topic=1564.0;attach=1279;image)

Pretty impressive eh?  Let’s look at some other sample rules that we could apply:

Sand:
Code: [Select]
Rule # Condition Action
1 Space below empty Move down
2 Space to the bottom-right/left empty Move to that empty space

Fire:
Code: [Select]
Rule # Condition Action
1 Space above is empty Move up
2 Space above is filled Move left/right
3 rand<.05 End life of this pixel

Acid:
Code: [Select]
Rule # Condition Action
1 Space below is not Acid Move down
2 Spaces to the sides is not acid Move either left or right
3 Single non-Acid space to a side Move into that empty space

Note that these are not the only way to achieve the effects desired, this is not a precise art, and many different rules can be applied to achieve many different effects, the best way to find out what works is to try everything yourself!

How To Use It:

Well that’s nice, how do I implement this in my program?  Well, it would be tempting to rely on pixel commands alone, but a more elegant solution is to have a list of pixel locations, and to loop through them.  This allows for better speed and a larger area of simulation.

Here is some sample code in Axe format:

Code: [Select]
For(F,0,N For N+1 Pixels
D*2+L1->L Find their location in L1
{L}->X X location in first Byte
{L+1}->Y Y location in second bytes
Pxl-Off(X,Y

If Pxl-Test(X,Y+1) If ground below is solid
  Rand^2*2-1->A Choose a random direction
  !If Pxl-Test(X+A,Y If that direction is empty
    X+A->X Move there
  Else!If Pxl-Test(X-A,Y Else, if the opposite direction is empty
    X-A->X Move there instead
  End
Else
  Y+1->Y If all else fails and ground below is empty, move down
End

Pxl-On(X,Y
X->{L}
Y->{L+1}
End
Note that this code won’t work by itself; you still need a way to put the pixels into L1, and to remove them.  You will also need to create the environment and everything, but this I leave up to you.

What to look out for:

I presented an option to store the pixels in an array, which takes a fair amount of memory.  It is tempting to just work off of the screen as a buffer, and loop through every pixel on it, but there is an inherent problem with this.  Not only does it limit the size of your screen, but the fact that you are either going to pass through the screen left to right, or right to left, introduces a bias into the simulation that might make fluids tend to flow left, or for smoke to drift right.  The results are unpredictable, and unless you know that the rules you introduce will not interfere, and that you have a small enough space to keep speed up, you should stick with the pixel buffer.
Title: Re: Physics Lessons
Post by: squidgetx on January 31, 2011, 09:37:07 pm
O.o great explanation!! The screenie is amazing too. I'll be sure to remember this whenever I want to do something physics based XD

Maybe I'll try and make a powdertoy....sorry qwerty :P nah I don't know the chem behind the he interactions of substances... Meh idk
Title: Re: Physics Lessons
Post by: Builderboy on January 31, 2011, 09:54:24 pm
Thanks :D I'm about to come out with a second about advanced pixel testing as well :) Building my way up to collision :P

EDIT: Interactions could simply be handled by rules :) Like if a piece of sand touches a piece of fire, it could become glass, or maybe become fire itself.  You would be free to decide how all the objects react and interact, independent of chemistry :)
Title: Re: Physics Lessons
Post by: Builderboy on January 31, 2011, 10:00:54 pm
Virtual Pixel Testing

We all know about the basic command Pxl-Test() right?  It tests a pixel on the screen/buffer and returns whether or not the pixel is on or off.  This seems simple enough, but actually can be used to provide some fairly quick alternatives to using matrix based collision detection.  Not only are we eliminating the need to a matrix, but by simply drawing to the screen, we have already generated the data we will need for collision.  Eliminating the Matrix, as well as the time needed to spend writing to it, mean that pxl-testing is a formidable way to speed up your Basic or Axe game!

But, there are some issues with this.  What happens when your game requires tiles that might not be solid black?  We run into problems fast if we have complicated graphics, and have to resort to complex trickery in order to get collision to work.  One option is to have a single pixel in each tile of a tilemap be the indicator on whether or not the tile is filled or not, but this is hardly a perfect solution.  What if we wanted to be able to detect alternate things?  Like for instance certain tiles might slow down your character, or make them enter a swimming animation. Certainly we can’t assign properties to all of the pixels of a sprite, that would be both slow and limiting in the graphics we could choose.  The solution lies in Virtual Pixel Testing.

A virtual pixel test is a test that behaves like a pixel test, but returns a value that doesn’t have to do with the pixels color.  Instead, it has to do with any attributes that the pixel has.  If we make this simple, we can have the virtual test determine whether or not the pixel is solid or not, independent of its color.  We could even expand this to return a value that relates to something like friction or temperature.  But how to implement such a function?  In this tutorial, I am going to be focusing on Tile Based Virtual Pixels, and Mask Based Virtual Pixels.

Tile Based Virtual Testing:

Say you have a tilemap, for any sort of game, sidescroller, top down, platform, you name it.  Chances are some of your tiles are going to need to be solid.  Now up until now, you have might gone by using some tricky byte testing mixed with modular arithmetic, wishing it were as simple as using a pxl-test() command.  Well, using virtual tests, it can be just as simple:

Code: [Select]
Lbl TST
{r2/8*W + (r1/8)+L1}
Return

Given a byte based matrix array located in L1, that represents a tilemap with width W, this function will return the tile number associated with any given pixel.  Note that r2/8*W is essential, r2*W/8 would not work.  

This simple function, coupled with clever ordering of your tiles, can make for very simple collision checking.  When you design your game, order the tiles so that all the solid ones come first, followed by all of the empty tiles.  This way, checking for a solid tile is as simple as a comparison test.  

Code: [Select]
Lbl TST
{r2/8*W + (r1/8)+L1}<N
Return

Where r1 is the X position, r2 is the Y position, N is the tile number where your empty tiles start, and L1 is the location of your matrix data buffer.

Using this routine will allow you to test a pixel and either get the tile number associated with that pixel (which could tell you any number of things) or test whether or not the tile is solid.  Using this information for accurate physics is now easier, and will be addressed in a later chapter.

Masked Virtual Buffer Testing:

This is all fine and dandy for tile based physics, but what about tiles that are not square?  Say you were making a sonic game, and you needed ramps and loops and things like that?  How could you modify this code such that it would work correctly?  The answer lies in Masks.

All a mask is, is an alternate sprite that tells you where your main sprite is solid.  If this is your normal sprite:

Code: [Select]
-------O
------OO
-----O-O
----O--O
---OOOOO
--O----O
-O-----O
OOOOOOOO

A simple ramp like sprite, then this is your sprite mask:

Code: [Select]
-------O
------OO
-----OOO
----OOOO
---OOOOO
--OOOOOO
-OOOOOOO
OOOOOOOO

Note that your regular sprite can be any design it wants to be, and your mask is black where it is solid and white where it is not.  The code for testing this is as follows:

Code: [Select]
Lbl MSK
{{r2/8*W+(r1/8)+L1}*8+(r2^8)+Str1}e r1
Return

Where r1 is your X position, r2 is your Y position, W is the width of your tilemap (in tiles), L1 is the location of your matrix data buffer, and Str1 is the start of your Mask Sprite table.

Your mask sprite table is identical to your sprite table, but instead of normal sprites, it includes the masked sprites.  This code will return the value of the bit in the mask sprite where your pixel is located, which can make for pixel based physics and terrain, in a tile based world.

What to watch out for:

Make sure that instead of using a variable W, use a constant!  Also try to make sure it is a power of 2, as this makes for very quick and simple multiplication.  You can further speed up both subroutines by changing the /8 into /2/2/2, although this will create an increase in size.  Also, the e in the mask operation is the euler's constant e found on the divide button.

Also note that all of the code in this lesson is based on the assumption that your pixel coordinates are based off of the upper left hand corner of your matrix, and that your matrix follows the left-to-right moving-down standard.  It also assumes you are using 8x8 sprites, although 16x16 sprites would not be difficult to accommodate.
Title: Re: Physics Lessons
Post by: ruler501 on January 31, 2011, 11:02:47 pm
this is wonderful it makes me want to go write a game. I'm amazed at how simple some of these things end up being.
Title: Re: Physics Lessons
Post by: Builderboy on February 01, 2011, 12:18:55 am
Everything is simple if it is explained in the right way :) I'm glad my tutorials are helping you :D
Title: Re: Physics Lessons
Post by: DJ Omnimaga on February 01, 2011, 12:28:08 am
Looks great. Shouldn't this be in the Axe sub-forum, though? Physics in BASIC would be kinda slow ???
Title: Re: Physics Lessons
Post by: Builderboy on February 01, 2011, 12:33:10 am
Good idea, I think i'll move it.  Some of the ideas are applicable, but its really only for Axe and Asm.  Do you think I should sticky it?
Title: Re: Physics Lessons
Post by: ruler501 on February 01, 2011, 09:03:03 am
Since i don't know axe, asm, or basic I'll try to use these for a python game. Physics this will be interesting
Title: Re: Physics Lessons
Post by: Binder News on February 01, 2011, 10:22:45 am
Good idea, I think i'll move it.  Some of the ideas are applicable, but its really only for Axe and Asm.  Do you think I should sticky it?
Definitely sticky it.
Title: Re: Physics Lessons
Post by: XVicarious on February 01, 2011, 06:57:52 pm
I was about to make a game involving falling objects too builderboy. nice. This is gonna help.
God... I wish i could redo this marking quarter in Physics. Screwed me over... 69...
Title: Re: Physics Lessons
Post by: AngelFish on February 01, 2011, 07:58:17 pm
O.o great explanation!! The screenie is amazing too. I'll be sure to remember this whenever I want to do something physics based XD

Maybe I'll try and make a powdertoy....sorry qwerty :P nah I don't know the chem behind the he interactions of substances... Meh idk

My engine is quite different from what Builderboy is describing, although the rules themselves are similar, so it's okay.

On a side note, be careful about array bounds. If you overflow, you can cause a pretty severe crash. But, even more than that, applying the rules to a lot of particles takes a lot of processing power. Keep the number of objects to a minimum.
Title: Re: Physics Lessons
Post by: ruler501 on February 03, 2011, 07:17:56 pm
Another good one to go here I believe is projectile motion. To get it realistic and efficient frame by frame can be complicated(at least to me)
Title: Re: Physics Lessons
Post by: Calcaholic on February 03, 2011, 07:24:27 pm
Do yout mean projectiles that are affected by gravity?
Otherwise I think that it would'nt be anything else than a routine like that (which is expressed in a general way):

Code: [Select]
loop
{
     [refresh position]
     [position+velocity]
}

Wouldn't it?

All in all doesn't projectile motion just include some of the tutorials that are already given?
(I ask dumb for my programming experiences are limitted to mostly personal experiments without any serious profession)
Title: Re: Physics Lessons
Post by: ruler501 on February 03, 2011, 07:38:04 pm
If launched at an angle it is more complex but It was explained to me so I don't think its as hard anymore. i still think there should be an article here for it though. I can't do it because I couldn't show sample code. I only know python and C++. these lessons are still applicable there which is why I'd like an article here
Title: Re: Physics Lessons
Post by: squidgetx on February 03, 2011, 07:38:56 pm
Builderboy: if you don't feel like it I could write one for you; I just explained it to ruler so I'm kinda in the mood lol ;)
edit: actually, it would probably be suitable as a small addition to the first post, about gravity...
Title: Re: Physics Lessons
Post by: Calcaholic on February 03, 2011, 08:02:04 pm
Could'nt you express that angle simply as gradient and split this gradient into a X- and a Y-velocity; where the y-velocity would be affected by gravity, while the x-velocity wouldn't?

But I can imagine, that this is horribly unoptimized... ;)
Title: Re: Physics Lessons
Post by: shmibs on February 04, 2011, 12:32:15 am
everyone has been going craxy over cellular automata recently, so i decided to make a quick little open-source demo to act as reference.
(http://img.removedfromgame.com/imgs/thisisalittlepowdertoydemonstratessomecellularautomatathateveryoneissokeenaboutthesedays.gif)
it most certainly isn't optimised (or even constructed in a matter which will allow particles to interact with one another beyond collisions), but it at least gets the idea across. ADA is the source. the controls are fairly straight-forward, involving nothing more than 2nd, alpha, and the arrow keys (and clear to quit).
Title: Re: Physics Lessons
Post by: AngelFish on February 04, 2011, 12:34:16 am
Now I'm forced to work on Powder. You know that right? :P

Good job otherwise.
Title: Re: Physics Lessons
Post by: DJ Omnimaga on February 04, 2011, 03:07:52 am
Nice shmibs. :D
Title: Re: Physics Lessons
Post by: Michael_Lee on February 04, 2011, 03:03:45 pm
Nice.  I like how the flames eat at the walls.

@ Builderboy: A while back, it looks like you were planning on adding a tutorial on collision detection?  Are you still planning on adding that?
Title: Re: Physics Lessons
Post by: kindermoumoute on February 05, 2011, 06:10:55 pm
Your tutorial is very interesting, but I fail to apply your phisic in my multiplayer game. I've 8 player maximum, each player got 4 bytes to him : X and Y position on tilemap, an other information and his velocity. So, the array to manipulate is :
Code: [Select]
{N*4+GDB0+A}N is actual player, and A is byte we want modify (1st, 2nd, 3rd or 4th).

Players take turns, but all must be attracted by gravity. M is total number of player. Here my bad code :
Code: [Select]
:Lbl G
:For(Θ,0,M)
:For(r3,0,{Θ*4+GDB0→r5+3}
:If sub(GN,5+{r5},4+{r5+1}+1)=0
{r5+1}+1→{r5+1}
:End
:End
:If sub(GN,5+{r5},4+{r5+1}+1)=0
:{r5+3}+A→{r5+3}
:Else
:0→{r5+3}
:End
:End
:Return
Subroutine GN extract byte from tilemap :
Code: [Select]
:Lbl GN
:r2*102+r1→r1
:{r1/2+D}→r2
:If r1^2
:r2^16
:Else
:r2/16
:End
:Return

Have you an idea ? ???

You understand that your physical system is very useful, especially for jumps. ;D
Title: Re: Physics Lessons
Post by: shmibs on February 07, 2011, 01:48:44 am
i was in la for the weekend and got bored, so i decided to clean up that little demo a bit and make it look more professional. the flames are now slightly more realistic, particles are displayed in gray when the program is run on an SE, and there are ? particles? (i think they're killer bees... :P)
Title: Re: Physics Lessons
Post by: Builderboy on February 07, 2011, 01:54:40 am
Alright, first, can't quite figure out what sub GN is suposed to do..  what does variable D mean?  It isn't used anywhere else in the code you posted.

Second, why are you looping from 0 to your velocity? For(r3,0,{Θ*4+GDB0→r5+3}) I think you want to move your character forward 1 space and check for collision each time?  Problems are going to arise when your velocity becomes negative.  I recommend switching to x256 format, since you are working with physics, and I recommend just incrementing your characters position by their velocity.  If they collide with an object, move them back to where they were before, and reverse the velocity.


EDIT: WOW thats an amazing application of cellular automata!  Outstanding! 
Title: Re: Physics Lessons
Post by: kindermoumoute on February 07, 2011, 01:28:58 pm
GN is not the problem, it return the good tile (D point appvars Data).
My problem is hard to explain (at least with my bad english), I want use your phisic in a multi-player game. How can I affect every players in same time I'm moving in a tilemap ?
Title: Re: Physics Lessons
Post by: DJ Omnimaga on February 07, 2011, 01:57:31 pm
Wow shmibs that is amazing! You should make a new thread about this. :)
Title: Re: Physics Lessons
Post by: Builderboy on February 07, 2011, 06:42:05 pm
GN is not the problem, it return the good tile (D point appvars Data).
My problem is hard to explain (at least with my bad english), I want use your phisic in a multi-player game. How can I affect every players in same time I'm moving in a tilemap ?

Ah you mean you have a scrolling tilemap?
Title: Re: Physics Lessons
Post by: kindermoumoute on February 08, 2011, 03:50:52 am
Yes, I would like to add phisic gravity in my worms game :
Spoiler For Spoiler:
(http://www.omnimaga.org/index.php?action=dlattach;topic=3328.0;attach=5681;image)

You can found the code here : here (http://ourl.ca/5925/166662) (a little old)
So, my gravity was this :
Code: [Select]
:Lbl G
:For(?,0,M)
:If sub(GN,5+{?*3+GDB0},5+{?*3+GDB0+1})=0 and (getKey(4)=0
:{?*3+GDB0+1}+1?{?*3+GDB0+1}
:End
:End
:Return
Your phisic system could be usefull to do some jump like here :
Spoiler For Spoiler:
(http://www.omnimaga.org/index.php?action=dlattach;topic=3328.0;attach=1393;image)
Title: Re: Physics Lessons
Post by: Builderboy on February 08, 2011, 11:17:44 am
Well first off, if you want realistic pysics, you might want to consider switching to x256 format.  This is where every time you add 256 to your position variables, your character moves 1 pixel.  This will allow you to have more precision and possibly get the gravity effects you are looking for.

However, If you do not want to use x256 format and stick with what you have, you can try this simple physics piece of code:

Code: [Select]
:Lbl G
:Θ*3+GDB0->r5
:If {r5+3}>>-7
:{r5+3}+1->{r5+3}
:End
:
:{r5+1}+{r5+3}->{r5+1}
:While sub(GN,{r5}+5,{r5+1}+5
:If {r5+3}>>0
:{r5+1}-1->{r5+1}
:Else
:{r5+1}+1->{r5+1}
:End
:End
:
:If sub(GN,{r5}+5,{r5+1}+5)=0 && getKey(4)
:-7->{r5+3}
:End
:Return

This piece of code *should* give you some realistic gravity and jumping in your game
Title: Re: Physics Lessons
Post by: leafy on February 12, 2011, 06:05:36 pm
How do you use tile masking with 5 by 5 tiles rather than 8 by 8 tiles?
Title: Re: Physics Lessons
Post by: kindermoumoute on February 13, 2011, 06:15:15 am
Well first off, if you want realistic pysics, you might want to consider switching to x256 format.  This is where every time you add 256 to your position variables, your character moves 1 pixel.  This will allow you to have more precision and possibly get the gravity effects you are looking for.

However, If you do not want to use x256 format and stick with what you have, you can try this simple physics piece of code:

Code: [Select]
:Lbl G
:Θ*3+GDB0->r5
:If {r5+3}>>-7
:{r5+3}+1->{r5+3}
:End
:
:{r5+1}+{r5+3}->{r5+1}
:While sub(GN,{r5}+5,{r5+1}+5
:If {r5+3}>>0
:{r5+1}-1->{r5+1}
:Else
:{r5+1}+1->{r5+1}
:End
:End
:
:If sub(GN,{r5}+5,{r5+1}+5)=0 && getKey(4)
:-7->{r5+3}
:End
:Return

This piece of code *should* give you some realistic gravity and jumping in your game
Your code don't work, no gravity affect my worms, and I don't understand what does it mean. :/
Title: Re: Physics Lessons
Post by: matthias1992 on February 13, 2011, 09:39:58 am
@builderboy.

could you roughly explain what you mean with x256 format? I can't  see the use of moving a pixel one unit by adding 256 to it instead of 1 (alas, that is what I am getting from what you said about it some posts up)

edit:

Awesome tuts by the way, imma digging it!! :D
Title: Re: Physics Lessons
Post by: Deep Toaster on February 13, 2011, 09:44:02 am
It's basically where your X and Y values are inflated (multiplied) by 256 for greater accuracy. In other words, when you actually display it, you'd use

Code: (Axe) [Select]
Pt-Change(X/256,Y/256,Pic0)

To move one pixel, then, you'd add 256 to either X or Y.

The point here is to simulate "half-pixels" and other fractions for the motion to seem smoother. For example, you could have the character move 1.5 pixels every frame by adding 384 to X instead of 256.
Title: Re: Physics Lessons
Post by: Builderboy on February 13, 2011, 12:44:32 pm
Well first off, if you want realistic pysics, you might want to consider switching to x256 format.  This is where every time you add 256 to your position variables, your character moves 1 pixel.  This will allow you to have more precision and possibly get the gravity effects you are looking for.

However, If you do not want to use x256 format and stick with what you have, you can try this simple physics piece of code:

Code: [Select]
:Lbl G
:Θ*3+GDB0->r5
:If {r5+3}>>-7
:{r5+3}+1->{r5+3}
:End
:
:{r5+1}+{r5+3}->{r5+1}
:While sub(GN,{r5}+5,{r5+1}+5
:If {r5+3}>>0
:{r5+1}-1->{r5+1}
:Else
:{r5+1}+1->{r5+1}
:End
:End
:
:If sub(GN,{r5}+5,{r5+1}+5)=0 && getKey(4)
:-7->{r5+3}
:End
:Return

This piece of code *should* give you some realistic gravity and jumping in your game
Your code don't work, no gravity affect my worms, and I don't understand what does it mean. :/

What happens to the worms?  What goes wrong?
Title: Re: Physics Lessons
Post by: kindermoumoute on February 15, 2011, 02:44:54 am
They don't move...
Title: Re: Physics Lessons
Post by: Waave on May 05, 2011, 09:50:40 pm
It's basically where your X and Y values are inflated (multiplied) by 256 for greater accuracy. In other words, when you actually display it, you'd use

Code: (Axe) [Select]
Pt-Change(X/256,Y/256,Pic0)

To move one pixel, then, you'd add 256 to either X or Y.

The point here is to simulate "half-pixels" and other fractions for the motion to seem smoother. For example, you could have the character move 1.5 pixels every frame by adding 384 to X instead of 256.

Thanks for this... I was wondering if there was a more elegant solution than just using 'Pause 250' at the end of my loop.
Title: Re: Physics Lessons
Post by: Builderboy on May 18, 2011, 07:10:51 pm
Single Segmented Rope Physics

   The situation is always the same, you are making your physics puzzle game that may or may not be a platformer, you want to add in a new game element, but you can't think of anything to add!  Maybe you want to add in some sort of rope element, but how in the world could we do this fast and efficiently?  Well this tutorial is going to teach you how to make a Single Segmented Force Based Rope Physics engine :D  That might sound complicated but lets break it down:

1) Single Segmented

    What single segmented means is that your rope will consist of only a single segment.  What this means is that we will only simulate the start and end of the rope, none of the stuff in the middle where the rope bends or whatnot.  Since one end of the rope is going to be fixed to a wall, in this tutorial we will only be simulating the object that is attached to the end of the rope.  When you go to display the rope however, you don't have to simply draw a line between the anchor and the object, you can get creative and do fancy things, but that is outside this tutorial.

2) Force Based

    There are many types of physics engines, and when combining them to create complicated effects, weird things can start to happen.  If one part of the physics engine devoted to rope physics moves an object without checking the other parts, it might accidentally move it into a wall or another object!  For this reason, the only thing this physics engine will do is impart forces onto the object, it will not move them.  We are also going to be assuming this rope is infinitely strong, and we will be ignoring the mass of the object.  By using only a force based engine, this gives us the highest possibility that this code will be able to be implemented into your existing engine.

3) The Conecpt

    So what happens to an object that is attached to a string?  What forces are exerted on it?  Before we can answer those questions, we need to decide how to define the string itself.  It needs an anchor point, and a length, so we will use three variables X,Y and L, to represent these.  We also need to use certain variables from our object, such as its position (I,J) and velocity (A,B).
 
Whenever the distance D from the object to the anchor is less than the length, we know that the rope is not going to be taught, and therefor cannot be imparting any force on the ball.  We could calculate the distance using the pythagorean theorem:

Code: [Select]
Sqrt((X-I)^2+(Y-J)^2)=D
But that uses a square root, and those are slow and sad.  Instead, we are going to square both sizes of the equation, since squaring is fast and happy!

Code: [Select]
(X-I)^2+(Y-J)^2=D^2
So now when we compare D to L, we will actually be comparing D^2 to L^2.  The size difference doesnt matter, since are only seeing if D is greater than L.  If you are using a x256 precision engine (which you should be :P) you can use this piece of code to find the distance in pixels (not x256!)

Code: [Select]
abs(X-I)->r1*^r1+(abs(Y-J)->r1*^r1)->D
So now we can tell if the object is pulling the string taught, or if it is letting it slack.  Obviously if it is slack (D<L) then we do not need to apply any force to the ball at all.  It is what happen when the string it taught (D>=L) that we start needing to apply a force. 

When a ball is moving out of the allowable ring of movement that the string allows, the first thing we need to do is eliminate the velocity that is taking it outside the ring.  This does not mean setting the velocity to 0.  This does also not mean we negate the velocity.  Imagine this:  The ball is falling straight down with the string above it.  When the string pulls taught, the ball will be yanked back up again and lose almost all velocity very quickly.  But if you drop it from an angle, off to the side, it will lose a little speed, but most of it will be transfered into a pendulum motion.  In a sense, all of the velocity that is directed out of the ring is being removed, and anything that is in line with the ring (tangential, its the motions it moves in when it swings) is kept.  Now this is a bit tricky to do, so bear with me here:

I-X//L->N
J-Y//L->O

This finds the Normal Vector of the string.  The math behind it isn't that important except that you know that it points in the same direction as the string, from base to object.  This will be important in determining how much velocity to remove, and from what direction to remove it from.  The string is the only thing that can take velocity from the object, and as such, it can only affect the object in the same direction the string is pointing.  The significance of this is that any change in the velocity of the object will be a multiple of this Normal Vector!  All that is left is to find this coefficient!

That coefficient just so happens to be the dot product of the objects velocity and the ropes normal vector.  A**N + (B**O)*-1->K
Spoiler For Spoiler:
Yeah, this isn't the 100% right dot product.  Technically speaking we would have to multiply two Normal Vectors, and AB is not normal.  But since we are going to be multiplying by AB anyways, we just combine the steps by not dividing and multiplying by AB :P I put this in a spoiler just because its pretty involved vector physics and not needed for the tutorial.  Similarly, multiplying by -1 isn't something that is done in a dot product, but is done later twice so i moved it back here so we only had to do it once :)

Now we need to do a quick test.  On the off chance that the ball is outside L, but actually moving *towards* the rope, K will be positive, and you don't want to affect the ball in this case.

Code: [Select]
If K<<0
Now all that is left to do is to add the velocity to the object!

Code: [Select]
K**N+A->A
K**O+B->B

Note that this will remove all velocity that is taking the ball outside the ring of string; stop it dead.  Sometimes this is undesired, so you can make it pull a little bit more and give the string a little "bounce"

Code: [Select]
K**N*3//2+A->A
K**O*3//2+B->B

And thats it!  You are done!  This is what the final result should look like when you piece all this together:
(Note that L^2 has been precomputed and put into M)

Code: [Select]
If abs(X-I)->r1*^r1+(abs(Y-J)->r1*^r1)<M
I-X//L->N
J-Y//L->O
A**N+(B**O)*-1->K
If K<<0
K**N*3//2+A->A
K**O*3//2+B->B
End
End

And this is what it should look like when implemented into a simple program!


Title: Re: Physics Lessons
Post by: leafy on May 18, 2011, 07:13:20 pm
Awesome! I was just about to ask you how in hell you got it to work so nicely ^^
Title: Re: Physics Lessons
Post by: Builderboy on May 19, 2011, 10:39:59 am
Yeah, I was surprised in the end how little lines of code I could do this in O.O  It took lots and lots of time to get it down to that level, the original even had 2 square root functions o.O
Title: Re: Physics Lessons
Post by: yunhua98 on May 19, 2011, 12:23:48 pm
amazing.  O.O
Title: Re: Physics Lessons
Post by: Munchor on May 19, 2011, 12:28:29 pm
O.O That is some short source code (AC.8XP). Thanks a lot Builderboy. However, I didn't get a word since I never used velocity and I didn't even get the first lesson so would I get this.

Nice job!
Title: Re: Physics Lessons
Post by: DJ Omnimaga on May 25, 2011, 04:29:57 am
Do I smell a Donkey Kong Country port? O.O (there were ropes and that stuff in the original game)
Title: Re: Physics Lessons
Post by: Darl181 on July 08, 2011, 07:21:39 pm
Quote from: http://ourl.ca/4279/169823 (masked sprites thing)
Code:
Lbl MSK
{r2^8+{r2/8*W+(r1/8)+L1}+Str1}e r1
Return


Where r1 is your X position, r2 is your Y position, W is the width of your tilemap (in tiles), L1 is the location of your matrix data buffer, and Str1 is the start of your Mask Sprite table.

I get what this does, but what exactly is the matrix data buffer?  Does it determine which sprite to read or something?


EDIT:
How do you use tile masking with 5 by 5 tiles rather than 8 by 8 tiles?
Quote from: line I don't understand completely but most of it I do :P
Where r1 is your X position, r2 is your Y position, W is the width of your tilemap (in tiles), L1 is the location of your matrix data buffer, and Str1 is the start of your Mask Sprite table.
Just change W, afaict ;)
Title: Re: Physics Lessons
Post by: squidgetx on July 08, 2011, 07:53:25 pm
I'm pretty sure he means "pointer to matrix data," since "buffer" typically refers to locations of free RAM
Title: Re: Physics Lessons
Post by: Darl181 on July 08, 2011, 07:54:20 pm
But the matrix part is what's confusing me.  What purpose does it serve?
Title: Re: Physics Lessons
Post by: squidgetx on July 08, 2011, 07:56:23 pm
I think it's just the pointer to the tilemap.
Title: Re: Physics Lessons
Post by: Darl181 on July 08, 2011, 07:58:31 pm
Ok, so what this does is it computes what square the (x,y) is inside of, then compares it to a sprite to see if that one bit is true? 
...in one line? O.O wow
Title: Re: Physics Lessons
Post by: squidgetx on July 08, 2011, 08:08:02 pm
Wait, Builderboy might've messed something up...let me give my (i think) fixed code with explanation
Code: [Select]
 

{{r2/8*W+   // get tile row, multiply by width
(r1/8)+   //get tile column
L1}*8+  // now we have the value of the tile you are in, then multiply by 8 because 8 bytes per sprite
(r2^8)+      //get pixel row # with respect to the tile you are in
Str1}    //we add this to the pointer to the mask table, thus returning the exact byte of the sprite mask
e r1    // and now we check if the appropriate pixel is lit or not in the given row
Return

Where r1 is your X position, r2 is your Y position, W is the width of your tilemap (in tiles), L1 is the location of your matrix data buffer, and Str1 is the start of your Mask Sprite table.
Title: Re: Physics Lessons
Post by: Darl181 on July 08, 2011, 08:38:27 pm
So, he put the *W in the wrong place?

Anyway, what I'm trying to do with this (and am not too sure how to implement) is detect an object that moves by 1,2,4, or 8 pixels every frame.  Would I have to make multiple sprites or something?
Title: Re: Physics Lessons
Post by: squidgetx on July 08, 2011, 10:59:22 pm
No, he forgot to multiply the tile value by eight.

You would not need multiple sprites, I don't think, just run a loop like any other variable velocity physics engine and use that piece of code for collision checks.
Title: Re: Physics Lessons
Post by: Darl181 on July 09, 2011, 12:22:09 am
Ok I'm kind of new to this physics stuff :P

What would the loop do, and where would it go? (I'm guessing just before the line above but you never know)
Title: Re: Physics Lessons
Post by: leafy on July 09, 2011, 01:13:15 am
So you're using 4x4 tiles. That's kind of a problem because your character can move at max 8 pix/frame, which means we can't simply move it back when it moves into a tile.
I would go with a for loop from 0 to the velocity, in which for each iteration you add one to your positional value, check it with the map, then if it's empty, keep going, and if it's occupied, move it back and stop the loop.
That's horribly inefficient, so I suggest going at max 1px/frame or if you really want to 3 px/frame with your 4x4 tiles.
Title: Re: Physics Lessons
Post by: Darl181 on July 09, 2011, 01:18:14 am
What I'm planning on doing after ds is 8*8 ;)
Title: Re: Physics Lessons
Post by: leafy on July 09, 2011, 02:08:10 am
Hm Builder's code worked for me though. I'll check and see what I did (I didn't end up using masked tiles in Graviter)
Title: Re: Physics Lessons
Post by: Darl181 on July 18, 2011, 01:49:36 pm
Bump,
Just to clarify I'm not writing a physics game atm, but I'm re-writing TWHG in a way that doesn't use all pixel-testing :P
So I'm testing for
  ████
████████
████████
  ████

b/c that's the enemy sprite (everything else atm is 8*8 squares)

Wait, Builderboy might've messed something up...let me give my (i think) fixed code with explanation
Code: [Select]
{{r2/8*W+   // get tile row, multiply by width
(r1/8)+   //get tile column
L1}*8+  // now we have the value of the tile you are in, then multiply by 8 because 8 bytes per sprite
(r2^8)+      //get pixel row # with respect to the tile you are in
Str1}    //we add this to the pointer to the mask table, thus returning the exact byte of the sprite mask
e r1    // and now we check if the appropriate pixel is lit or not in the given row
Return
Where r1 is your X position, r2 is your Y position, W is the width of your tilemap (in tiles), L1 is the location of your matrix data buffer, and Str1 is the start of your Mask Sprite table.
So, do I need a masked sprite for everything or just the one tile?  I'm guessing a tile value (from L1) of 0 is the first sprite, 1, second sprite, etc?
Title: Re: Physics Lessons
Post by: willrandship on October 10, 2011, 07:34:56 pm
So, I've actually compiled these into a FlashBook App, so now you can have them in a single-page app on your calc! It's only compressed at lv. 1, so you don't need to have any free RAM available either (Either way it would have taken a whole page)

Enjoy!  :trollface:
Title: Re: Physics Lessons
Post by: parserp on October 10, 2011, 07:39:09 pm
sweet thanx!!! +1 by the way
Title: Re: Physics Lessons
Post by: boot2490 on October 10, 2011, 09:55:42 pm
man, EVERYBODY is using my trollface!
Together, we will take over the web! :trollface:
Title: Re: Physics Lessons
Post by: willrandship on October 10, 2011, 10:40:20 pm
I should have stuck it in the tut app :P I had about 2k of space left in the page......

Edit: Done! :trollface: Check the bottom  >:D