控制精灵套件中的最大速度

我试图在我的游戏中控制angular色的最大速度。 当我移动他时,我使用这个:

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event { UITouch *touch = [touches anyObject]; CGPoint positionInScene = [touch locationInNode:self]; SKSpriteNode *touchedNode = (SKSpriteNode *)[self nodeAtPoint:positionInScene]; CGPoint posicionHero = [self childNodeWithName:@"hero"].position; SKSpriteNode *touchHero = (SKSpriteNode *)[self nodeAtPoint:posicionHero]; if((touchedNode !=touchHero) //jump forward && (positionInScene.x > [self childNodeWithName:@"Hero"].position.x) && (positionInScene.y > [self childNodeWithName:@"Hero"].position.y) ) { [[self childNodeWithName:@"Hero"].physicsBody applyImpulse:CGVectorMake(5,0)]; [[self childNodeWithName:@"Hero"].physicsBody applyImpulse:CGVectorMake(0, 10)]; NSLog(@"jump forward done"); } 

但是问题是速度不是有限的,而且当我这样做了两三次的时候,angular色走得很快。 我尝试了很多属性(速度,angular速度等),我没有发现任何令人满意的东西。 有人知道如何设置一个速度限制或任何“伎俩”来控制一个angular色的最大速度?

这是行之有效的。

 - (void)didEvaluateActions { CGFloat maxSpeed = 600.0f; if (self.heroShip.physicsBody.velocity.dx > maxSpeed) { self.heroShip.physicsBody.velocity = CGVectorMake(maxSpeed, self.heroShip.physicsBody.velocity.dy); } else if (self.heroShip.physicsBody.velocity.dx < -maxSpeed) { self.heroShip.physicsBody.velocity = CGVectorMake(-maxSpeed, self.heroShip.physicsBody.velocity.dy); } if (self.heroShip.physicsBody.velocity.dy > maxSpeed) { self.heroShip.physicsBody.velocity = CGVectorMake(self.heroShip.physicsBody.velocity.dx, maxSpeed); } else if (self.heroShip.physicsBody.velocity.dy < -maxSpeed) { self.heroShip.physicsBody.velocity = CGVectorMake(self.heroShip.physicsBody.velocity.dx, -maxSpeed); } } 

感谢@Andrew和@ LearnCocos2D&@Andy的评论

你可以用这个

 - (void)didSimulatePhysics 

委托SKScene的方法来检查节点的物理体的速度,并将其设置为您想要的最大速度。

 - (void)didSimulatePhysics { if (node.physicsBody.velocity.x < MAX_SPEED_X) { node.physicsBody.velocity = CGVectorMake(MAX_SPEED_X, MAX_SPEED_Y); } } 

您可能需要为速度的Y方向添加另一个检查。

对我来说最好的办法是以下几点,因为它确保vector速度在对angular线上不会更快:

  /* Clamp Velocity */ // Set the initial parameters let maxVelocity = CGFloat(100) let deltaX = (self.physicsBody?.velocity.dx)! let deltaY = (self.physicsBody?.velocity.dy)! // Get the actual length of the vector with Pythagorean Theorem let deltaZ = sqrt(pow(deltaX, 2) + pow(deltaY, 2)) // If the vector length is higher then the max velocity if deltaZ > maxVelocity { // Get the proportions for X and Y axis compared to the Z of the Pythagorean Theorem let xProportion = deltaX / deltaZ let yProportion = deltaY / deltaZ // Get a new X and Y length in proportion to the max velocity let correctedDeltaX = xProportion * maxVelocity let correctedDeltaY = yProportion * maxVelocity // Assign the new velocity to the Node self.physicsBody?.velocity = CGVector(dx: correctedDeltaX, dy: correctedDeltaY) }