1
votes

I'm trying to move an SKSpriteNode in an arc with physics in spritekit like so: enter image description here

But am unsure as to which physic I should apply to it (applyImpulse, applyForce, applyTorque).

Currently using applyTorque, the code does not actually work, and produces no movement on the object:

_boy.physicsBody.velocity = CGVectorMake(1, 1);
CGVector thrustVector = CGVectorMake(0,100);
[_boy.physicsBody applyTorque:(CGFloat)atan2(_boy.physicsBody.velocity.dy, _boy.physicsBody.velocity.dx)];
1
How about applying a force. E.g. 2 pts X directions and 1 pt Y?Rob Sanders

1 Answers

0
votes

applyTorque is not the right method for this. Torque is a twisting force that causes your node to rotate around its center point.

There is no one easy command for what you are looking to do. You also fail to mention your method of movement for your node. Apply force, impulse, etc... You are going to have to come up with a hack for this one.

The sample project below does what you are looking for and it will point you in the right direction. You are going to have to modify the code to suit your specific project's needs though.

Tap/click the screen once to start moving the node and tap/click the screen a second time to start to 90 degree movement change.

#import "GameScene.h"

@implementation GameScene {
    int touchCounter;
    BOOL changeDirection;
    SKSpriteNode *node0;
}

-(void)didMoveToView:(SKView *)view {
    self.backgroundColor = [SKColor whiteColor];

    node0 = [SKSpriteNode spriteNodeWithColor:[SKColor grayColor] size:CGSizeMake(50, 50)];
    node0.position = CGPointMake(150, 200);
    node0.physicsBody = [SKPhysicsBody bodyWithRectangleOfSize:node0.size];
    node0.physicsBody.affectedByGravity = NO;
    [self addChild:node0];

    touchCounter = 0;
    changeDirection = NO;
}

-(void)update:(CFTimeInterval)currentTime {
    if(changeDirection)
        [self changeMovement];
}

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    touchCounter++;

    for (UITouch *touch in touches) {
        if(touchCounter == 1)
            [node0.physicsBody applyImpulse:CGVectorMake(25, 0)];
        if(touchCounter == 2)
            changeDirection = YES;
    }
}

-(void)changeMovement {
    if(node0.physicsBody.velocity.dy<200) {
        [node0.physicsBody applyImpulse:CGVectorMake(-0.1, 0.1)];
    } else {
        changeDirection = NO;
        node0.physicsBody.velocity = CGVectorMake(0, node0.physicsBody.velocity.dy);
    } 
}