Game Development Reference
In-Depth Information
currentPos.x = self.bounds.size.width - sprite.size.width;
xVelocity = 0.0f;
if(currentPos.y > self.bounds.size.height - sprite.size.height){
currentPos.y = self.bounds.size.height - sprite.size.height;
yVelocity = 0.0f;
CGRect curSpriteRect = CGRectMake(currentPos.x, currentPos.y,
currentPos.x+sprite.size.width, currentPos.y+sprite.size.height);
CGRect prevSpriteRect = CGRectMake(prevPos.x, prevPos.y,
prevPos.x+sprite.size.width, currentPos.y+sprite.size.height);
[self setNeedsDisplayInRect:CGRectUnion(curSpriteRect, prevSpriteRect)];
In case you are unfamiliar with Objective-C, when you define a class instance variable
it will automatically define a mutator that simply updates the value of the variable to
the value you are passing it. However, in the preceding example we are overriding that
mutator to do some additional work. The first thing we do is to set the prevPos variable
to the current position of the sprite and then update the currentPos with the value the
mutator was given. However, our physics engine isn't going to include collision response
with the screen boundaries, so we go on to check if the sprite has reached the screen
edge. If so, we simply tell the program to leave it on the edge and to set the velocity in
that direction to 0. Lastly, we define a couple of rectangles based on the new position of
the sprite and the old position of the sprite. After we union those rectangles together,
we tell the operating system to redraw the screen in that area with the setNeedDis
playInRect: method. As you might recall, our accelerometer object is calling the draw
method every time it updates, and it is in this method that we will put our physics engine:
- (void)draw {
static NSDate *lastUpdateTime;
if (lastUpdateTime != nil) {
NSTimeInterval secondsSinceUpdate = -([lastUpdateTime
timeIntervalSinceNow]); //calculates interval in seconds from last update
//Calculate displacement
CGFloat deltaX = xVelocity * secondsSinceUpdate +
((acceleration.x*g*secondsSinceUpdate*secondsSinceUpdate)/2); // METERS
CGFloat deltaY = yVelocity * secondsSinceUpdate +
((acceleration.y*g*secondsSinceUpdate*secondsSinceUpdate)/2); // METERS
//Converts from meters to pixels based on defined World size
deltaX = deltaX * convertX;
deltaY = deltaY * convertY;
//Calculate new velocity at new current position
xVelocity = xVelocity + acceleration.x * g * secondsSinceUpdate; //assumes
acceleration was constant over last update interval
Search Nedrilad ::

Custom Search