Flash Physics Study - Page 4
Posted by : awesty on Jun 28, 2008
Now, you might be asking how we got the z-direction upper and lower bounds of 100 and 0 since there really is no z-direction. Well, these are arbitrary, but we'll use the upper and lower limits to later define how large in scale the ball should be to appear as if its coming closer or going farther away from you as we discussed in the beginning.
Finally, you'll see that we account for friction of the floor by readjusting the x and z velocities every time the ball hits the floor. This coefficient of friction is a number between 0 and 1 (with 0 as a maximum friction and 1 as a floor with absolutely no friction).
In this third and final block of ball-logic code, we now actually move the ball into its new position, and set the "old" position values to the current ones, so we are ready to do this process over again: // Set the old coordinate values to the new ones... oldPositionY = positionY; oldPositionX = positionX; oldPositionZ = positionZ;
// For the Z-direction, let's set the scaling and alpha
// to fake the 3-d
this._alpha = ((positionZ / 100) * 30) + 70;
this._height = ((positionZ / 100) * 8) + 2;
this._width = ((positionZ / 100) * 8) + 2;
// For x,y, just set the coordinate values to the x,y values
this._y = positionY;
this._x = positionX;
So, now the x and y positions are easy to understand. We just set the _x and _y properties of our movieclip to the new positions. What's the deal with the z position, then?
Well, what we are doing here is taking the value of the new z-position (which I predefined earlier as any value between 0 and 100) and getting a percentage of the maximum. Then, I multiply by a range, and add the entire value by a lower bound. So, if you take the _height property, the range of values would be 2 to 10 (2 + 8).
Also, I've thrown in an equation to change the _alpha of the movieclip, so that things farther away are slightly less apparent than things closer to you (the range of alphas is 70 to 100).
So, there it is. We've built our logic base for a bouncing ball. Now, using trusty duplicateMovieClip(), you can create all sorts of balls that jump around and do their own thing, within the confines of the rules we've set up for them here. I've thrown in a few sliders on the root timeline so that you can change the gravity constant, friction, and amount of balls on stage. Also, the initial x,y, and z velocities are randomized, and the initial x,y, and z positions all start at the same spot. I won't go into the implementation of these, since they don't pertain to this article, but the source code is available if you're curious.
And, that's it. Hopefully, you've learned a little something about how to implement a bit of physics into your Flash applications, and learned how and when to fake some of it.

no comment
Add comment