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

送分小仙女□ 提交于 2019-12-11 07:39:59

问题


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:(ccTime) 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.


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/7162685/how-to-simulate-a-gravity-for-one-sprite-in-cocos2d-without-a-physics-engine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!