Gravity is nothing more than a constant velocity applied to the body for each step of physics. Take a look at this sample update method:
-(void) update:(ccTime)delta { // use a gravity velocity that "feels good" for your app const CGPoint gravity = CGPointMake(0, -0.2); // update sprite position after applying downward gravity velocity CGPoint pos = sprite.position; pos.y += gravity.y; sprite.position = pos; }
In each frame, the position of the sprite y will be reduced. This is a simple approach. For a more realistic effect, you will need a velocity vector for each moving object and apply gravity to the velocity (which is also CGPoint).
-(void) update:(ccTime)delta { // use a gravity velocity that "feels good" for your app const CGPoint gravity = CGPointMake(0, -0.2); // update velocity with gravitational influence velocity.y += gravity.y; // update sprite position with velocity CGPoint pos = sprite.position; pos.y += velocity.y; sprite.position = pos; }
This leads to the fact that the speed, with time, increases in the downward direction y. This will accelerate and accelerate the object faster, the longer it "falls".
However, by changing the speed, you can still change the general direction of the object. For example, to make a character jump, you can set velocity.y = 2.0 , and it will move up and down again due to the gravity effect applied over time.
This is still a simplified approach, but very common in games that do not use the โrealโ physics engine.
source share