March 14, 2014

The Physical System

At this point, we have a solid framework, an engine core to kick off the game loop, and a sprite system to render and animate graphics. The next step is to make our entities mobile. We will accomplish this by adding a Physics component to our movable entities that contains data about velocity and how the entity should respond to things like gravity.

For now, the two pieces of data needed in the Physics component are velocity and a boolean value that indicates whether the entity should respond to gravity. Velocity is a vector, and it can be represented as an (x, y) pair, so for my component I used a CGPoint. The x-component corresponds to the horizontal speed of the entity, and the y-component corresponds to the vertical speed of the entity. Velocity defaults to CGPointZero. respondsToGravity is a boolean value that defaults to YES.

The Physical System that controls movable entities is simple, and only has the responsibility of updating velocity and position. The system itself has a gravity vector with which it updates each entity’s velocity and a terminal velocity vector that limits the magnitude of all velocities. Finally, the system applies each entity’s velocity to its position.

@implementation LGPhysicalSystem

@synthesize gravity, terminalVelocity;

- (BOOL)acceptsEntity:(LGEntity *)entity
{
	return [entity hasComponentsOfType:[LGPhysics class], [LGTransform class], nil];
}

- (void)update
{
	for(LGEntity *entity in self.entities)
	{
		LGPhysics *physics = [entity componentOfType:[LGPhysics class]];
		LGTransform *transform = [entity componentOfType:[LGTransform class]];
		
		if([physics respondsToGravity])
		{
			[physics addToVelocity:gravity];
			[physics limitVelocity:terminalVelocity];
		}
		
		[transform setPrevPosition:[transform position]];
		[transform addToPosition:[physics velocity]];
	}
}

Now we can make our entities move and respond to gravity. Some entities may not respond to gravity, such as a floating platform, so the Physics component can choose to ignore gravity in these cases. If we add this component to any entities right now, however, we’ll run into a problem. Rather, we won’t run into anything — gravity will apply indefinitely and all of the entities will fall off the screen. Before we can add this, then, we’ll need to create a collision system, which I will describe in the next post.

Posted by Luke Godfrey

Luke Godfrey is a graduate student at the University of Arkansas, pursuing a PhD in Computer Science. He has created applications on a number of platforms, and is especially interested in mobile and web development.

View more posts from this author

Leave a Reply

Your email address will not be published. Required fields are marked *