Crazycriss
Crazycriss

Reputation: 315

Sprite Speed Cocos2d 3.0

This is the code running my sprite, it's supposed to jump smoothly and start from the center of the screen. Which it does, occasionally, but most of the time it crashes down to the floor. It still jumps, but it's not smooth.

Float value

@interface HelloWorldScene () <CCPhysicsCollisionDelegate>
{
float           _yVel;
}

@end

Math

- (void) jump
{
// adjust jump speed here
if ( _player.position.y > kFLOOR_HEIGHT ) _yVel -= 0.14;
else {
    if ( _yVel != 5 ) _yVel = 0;
}

_player.position = ccp( _player.position.x, _player.position.y + _yVel);
}

Can someone help with this?

Upvotes: 0

Views: 145

Answers (1)

Felizardo
Felizardo

Reputation: 298

I couldn't understand everything your code does, you should share more information (For instance, when does the jump message is sent ? Is when the user touches some screen button?)

However, I can give you some tips to improve it:

  • Avoid creating attributes like _yVel, use the physicsBody.velocity instead. As I can see you are using physics (because of CCPhysicsCollisionDelegate), so you do not need to reinvent the wheel to simulate a body velocity.
  • The best way to achieve a "jump" is applying some impulse/force to a physicsBody instead of changing directly the velocity. If you also use a gravity, it will give you the "smooth" falling effect, generally found on platform genre games.
  • You should never compare a floating number like _yVel with another exact number, like you did in if ( _yVel != 5 ) _yVel = 0;. This is very straight-forward to understand, as a very close number to 5 like 5.00001 will return YES to the condition. If you really need to do something like that, you should use intervals instead, like if ( _yVel >= 4.5 && _yVel <= 5.5 ) ...

EDIT: This great tutorial will help you https://www.makegameswith.us/gamernews/369/build-your-own-flappy-bird-with-spritebuilder-and

Upvotes: 1

Related Questions