static float tuna = 10.0f;
-(void) reset
{
float vy = 0.0f;
float vx = 0.0f;
int sign = 1;
if (CCRANDOM_0_1() >= 0.5) {
sign = -1;
}
float hurry = 0.0f;
if (CCRANDOM_0_1() <= 0.1) {
hurry = 1.0f;
}
switch (birdType) {
case BirdType1:
vx = 1.0f * sign + (CCRANDOM_0_1() - 0.5f) * 0.08f;
vy = -6.5f;
break;
case BirdType2:
vx = 1.5f * sign + (CCRANDOM_0_1() - 0.5f) * 0.08f;
vy = -6.2f + (CCRANDOM_0_1() - 0.5f) * 0.1f;
break;
case BirdType3:
vx = 1.0f * sign + (CCRANDOM_0_1() - 0.5f) * 0.1f;
vy = -5.8f - hurry;
break;
default:
[NSException exceptionWithName:@"BirdMoveComponent exception" reason:@"unhandled bird type" userInfo:nil];
break;
}
velocity = CGPointMake(vx * 5, vy * 5);
if ((int)([[GameManager sharedManager] score] / 100) >= prevLevel) {
if (tuna <= 12.0f) {
tuna += 0.01f;
}
prevLevel = (int)[[GameManager sharedManager] score] / 100;
}
}
-(void) update:(ccTime) delta
{
if (self.parent.visible) {
NSAssert([self.parent isKindOfClass:[BirdEntity class]], @"node is not an entity");
BirdEntity* bird = (BirdEntity*) self.parent;
bird.position = ccpAdd(bird.position, ccpMult(velocity, delta * tuna));
velocity = ccpAdd(velocity, ccpMult(acceleration, delta * tuna));
acceleration = ccp(0, 0.3f);
float birdHeight = CGRectGetHeight([bird boundingBox]);
//20 is the bottom trap
if (bird.position.y <= (birdHeight / 2) + 20) {
[bird dieAccidently];
}
if (CGRectIntersectsRect([GameScene screenRect], [bird boundingBox]) == NO)
{
bird.visible = NO;
[bird stopAllActions];
[bird unscheduleAllSelectors];
[bird unscheduleUpdate];
[self reset];
}
}
}
答案 0 :(得分:2)
物体的位置可以从等式系统计算:
x = Vx * t + x0
y = (-g*t*t)/2 + Vy * t + y0
,其中g - 重力加速度,V - 初始速度,Vx和Vy - 分别在X轴和Y轴上的投影。
问题是什么是最高点,即我们需要找到MAX(y(t))。
衍生物:y'(t) = -g*t + Vy.
y'(t) should equals zero, -g*t + Vy = 0; t = Vy/g; MAX(y) = y(Vy/g) = Vy*Vy/2g.
MAX(y) = Vy*Vy/2g + y0 // ballistic trajectory
MIN(y) = y0 - Vy*Vy/2g // your case
如果你想让你的小鸟Y在一定范围内,你应该计算出与此相关的速度。
增加:
btw是否有一个示例cocos2d代码 抛物线?
这是我的工作代码。
- (void) update: (ccTime)dt
{
t += dt*20;
...
[self getVertices];
}
- (void) getVertices
{
//for every index: {
...
//getting initial position (x0, y0)
...
vertices[index] = ccpAdd(vertices[index], ccpMult(velocity[index/3], t * screenFactor)); //+velocity*t
vertices[index] = ccpAdd(vertices[index], ccpMult(gravity, (t*t/2) * screenFactor)); //+acceleration*t^2 /2
//}
}
1)如您所见,每次都无需计算速度:使用初始速度。 2)顶点是当前Sprite位置的CGPoint数组。 3)t(当前时间),顶点,重力,速度是普通类的实例变量。