Game Development Reference
In-Depth Information
yVelocity = yVelocity - (acceleration.y * g * secondsSinceUpdate); //assumes
acceleration was constant over last update interval
//Mutate currentPos which will update screen
self.currentPos = CGPointMake(self.currentPos.x + deltaX,
self.currentPos.y + deltaY);
[lastUpdateTime release];
lastUpdateTime = [[NSDate alloc] init];
Previously, we discussed issues with timing when working with accelerometer data. In
this case, Objective-C makes it very easy to get the correct elapsed time in seconds. We
first define a static variable, lastUpdateTime , as an NSDate type. This type has a built-
in function to give the time interval in seconds from now, which we assign to an NSTime
Interval variable. Skipping down to the last two lines, we are simply updating the last
update time by releasing and reinitializing the variable. As it is static, it will remain even
after the function returns. If you are using a lower-level language, you might have to
write your own timeIntervalSinceNow function that takes into account the particular
clock frequency of the system.
Now that we have our time interval in seconds, we can calculate our new position. Recall
from Chapter 2 :
s 2 = s 1 + v 1 t + (a t 2 )/2
which we have rearranged to be:
Δs = s 2 − s 1 = v 1 t + (a t 2 )/2
This gets programmed as:
CGFloat deltaX = xVelocity * secondsSinceUpdate +
((acceleration.x*g*secondsSinceUpdate*secondsSinceUpdate)/2); // METERS
We then convert this displacement in meters to displacement in pixels using an appro‐
priate ratio for the size of our world. Before we can move on, we have to calculate our
new velocity at our new position. So we again assume the acceleration as constant over
the update interval, and recalling:
v 2 = v 1 + a Δt
from Chapter 2 , we can solve for the new xVelocity with:
xVelocity = xVelocity + acceleration.x * g * secondsSinceUpdate;
Search Nedrilad ::

Custom Search