问题
I am working on a simple game where a player advances up through a level by collecting coins. Each coin that the player collects moves them further in the level. Here is a picture that explains it a little more:
There are two different kinds of coins - regular coins and 'special' coins. Regular coins give them a normal boost. Special coins should give the player a temporary extra boost.
Special coins can always be found in the middle of regular coin group (As shown in the picture). My problem is that when a user hits a special coin it only gives them the boost for a split second because they end up hitting a regular coin almost immediately after.
I have tried 3 different options with none of them working as I planned.
Option 1 - (Problem- A 'special' star will give them a split second boost, but almost immediately the player gets set back down to regular speed when they touch a normal star)
if starType == .Special {
player.physicsBody?.velocity = CGVector(dx: player.physicsBody!.velocity.dx, dy: 900.0)
}
else {
player.physicsBody?.velocity = CGVector(dx: player.physicsBody!.velocity.dx, dy: 500.0)
}
Option 2- Use SKAction to delay 3 seconds after touching special star so that it does not read anything from regular star(Problem- same as above)
if starType == .Special {
let wait = SKAction.waitForDuration(3)
let boost = SKAction.runBlock({
player.physicsBody?.applyImpulse(CGVector(dx: 0.0, dy: 80.0))
})
let action = SKAction.group([boost, wait])
player.runAction(action)
}
else {
player.physicsBody?.velocity = CGVector(dx: player.physicsBody!.velocity.dx, dy: 500.0)
}
Option 3 - Use impulses instead of setting a new velocity. (Problem- each impulse adds to the last one, making the player go SUPER fast and finishing the level in a matter of seconds)
if starType == .Special {
player.physicsBody?.applyImpulse(CGVector(dx: 0.0, dy: 90.0))
}
else {
player.physicsBody?.applyImpulse(CGVector(dx: 0.0, dy: 40.0))
}
Any suggestions for a better implementation would be great.
Thanks
回答1:
I suggest using option three + checking to see if the y velocity is too high, then to lessen or not do the boost at all.
if starType == .Special && player.physicsBody?.velocity.dy <= 40 {
//40 is just an example number
player.physicsBody?.applyImpulse(CGVector(dx: 0.0, dy: 90.0))
}
else {
player.physicsBody?.applyImpulse(CGVector(dx: 0.0, dy: 40.0))
}
You could also change the impulse depending on what the current velocity is. It all depends on what you want the mechanics to be, and what the max velocity should be.
来源:https://stackoverflow.com/questions/32290323/applying-impulses-in-spritekit