开发者

How to simulate a gravity for one sprite in cocos2d without a physics engine?

I would like to simulate "gravity" for one sprite.

I defined a CGPoint which holds the gravity values. And I have tick method.

//in my init I defined this: gravity = ccp(0.0f, -1.0f);
-(void)tick:(ccTim开发者_StackOverflowe) dt {
if (enableGravity_) {
    //simulate gravity
    velocity_.x += gravity_.x;
    velocity_.y += gravity_.y;
    self.position = CGPointMake(position_.x + velocity_.x, position_.y + velocity_.y);
}    
if (isAcceleratingEnabled_) { //I move my sprite here
    float angle = self.rotation;
    float vx = cos(angle * M_PI / 180) * acceleratingSpeed_;
    float vy = sin(angle * M_PI / 180) * -acceleratingSpeed_;
    CGPoint direction = ccp(vx, vy);

    [self setPosition:ccpAdd(self.position, direction)];
}

}

EDIT: the problem now is..I'm moving my sprite if "isAccelerationEnabled" is YES. And it's not smooth when I move the sprite like that. If I move my sprite upwards and than disable the "isAcceleration" it won't move upwards anymore but the gravity will INSTANTLY pull my sprite down. I don't know how to use the velocity with this code:

[self setPosition:ccpAdd(self.position, direction)];

Now this isn't a really smooth solution to simulate gravity.

This applies the gravity force instantly to the sprite.

But I want the effect that the sprite falls smoothly. Like real objects fell to earth.

Btw: I also apply some upward forces to the sprite.


The problem is that you're applying gravity as a velocity rather than an acceleration. You need to give your sprite a velocity, then do something like...

sprite.velocity = ccp(self.velocity.x+gravity.x, self.velocity.y+gravity.y);
sprite.position = ccp(sprite.position.x+sprite.velocity.x, sprite.position.y+sprite.velocity.y);

Also if you're only ever going to do gravity pulling downward, it doesn't need to be 2D, it can just be a scalar that always applies in the negative Y direction.


Now that you have introduced velocity variables, the controls vx and vy should also be applied to the velocity instead of position. This corresponds to applying a constant force to the object, which is quite realistic, but may not be the kind of control you want.

Another approach is to simply assign vx to velocity_.x and vy to velocity_.y in the isAccelerationEnabled_ branch. This corresponds to applying as large a force as necessary whenever you actively control the object. If it looks too unrealistic, you might want to limit the velocity change to some maximum value.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜