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

Alf*_*fro 3 objective-c ios sprite-kit

我试图在游戏中控制角色的最大速度.当我移动他时我使用它:

-(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");
}
Run Code Online (Sandbox Code Playgroud)

但问题是速度不受限制,当我这样做两到三次时,角色变得非常快.我尝试了很多属性(速度,角速度等),我没有找到任何令人满意的东西.有人知道如何设置速度限制或任何"技巧"来控制角色的最大速度吗?

Gad*_*ter 5

这运作良好。

- (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);
    }
}
Run Code Online (Sandbox Code Playgroud)

感谢@Andrew的回答以及@LearnCocos2D和@Andy的评论


Tok*_*iku 5

对我来说最好的方法是以下因为它确保了对角线中的矢量速度不快:

    /* 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)
    }
Run Code Online (Sandbox Code Playgroud)