Game Development Reference
In-Depth Information
(140, 210). The vector bodyToFingerDirection is now (140, 210). It's called the
direction from bodyPos to fingerPos because if you added bodyToFinger-
Direction to bodyPos , you'd get to the coordinates of fingerPos .
Note The b2Vec2 struct makes use of a technique called operator overload-
ing, which makes it possible to subtract, add, or multiply two or more b2Vec2
structs with each other. Operator overloading is a feature of the C++ language;
it's not available in Objective-C—so you can't subtract, add, or multiply
CGPoint variables this way.
So, the bodyToFingerDirection vector is now pointing from the body to the fin-
ger. When Normalize is called on the bodyToFingerDirection vector, it's
turned into a unit vector , as mentioned earlier. A unit vector is a vector of length 1—or
one unit. This allows you to multiply it with a fixed factor, in this case doubling its
length, to create a constant force vector pointing in the direction of the finger. You can
then use the ApplyForce method of the body to apply this as an external force to the
body's center. You could also use a position other than the center, but in that case, the
body would start spinning.
The end result is that the ball accelerates toward the point on the screen that your finger
is touching. The ball will usually overshoot, slow down, and return. A little bit like the
gravitational pull the sun exerts on our planet, albeit a lot more dramatically.
However, as someone interested in astronomy, I do have to correct myself. Gravity is a
force that falls off by the square of the distance between two objects pulling on each
other. If you want a more realistic simulation of gravity in your game, simply replace
the applyForceTowardsFinger code with that in Listing 13-11 .
Listing 13-11 . Simulating Gravitational Pull
-(void) applyForceTowardsFinger
{
b2Vec2 bodyPos = physicsBody- > GetWorldCenter();
b2Vec2 fingerPos = [Helper toMeters:fingerLocation];
float distance = bodyToFingerDirection.Length();
bodyToFingerDirection.Normalize();
 
 
Search Nedrilad ::




Custom Search