问题描述
我想为一个sprite模拟重力。
I would like to simulate "gravity" for one sprite.
我定义了一个保存重力值的CGPoint。
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 :
现在的问题是...如果isAccelerationEnabled为YES,我将移动我的sprite。当我移动精灵像这样不顺利。
如果我向上移动我的sprite,而禁用isAcceleration,它不会再向上移动,但重力会永远拉我的sprite下来。我不知道如何使用速度与此代码:
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:我也对sprite使用一些向上的力。
Btw: I also apply some upward forces to the sprite.
推荐答案
问题是你应用重力作为速度而不是加速度。你需要给你的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);
此外,如果你只是想做重力向下拉,它不需要2D,它可以只是一个标量,总是应用在负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.
这篇关于如何在没有物理引擎的cocos2d中模拟一个sprite的重力?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!