2
votes

I am working on a game where a bunch of enemies spawn outside the screen and move towards the center (where there's a space station). However, I need the spaceships to face in the direction of the center. Currently, I'm using this code:

- (void)rotateNode:(SKNode *)nodeA toFaceNode:(SKNode *)nodeB {

double angle = atan2(nodeB.position.y - nodeA.position.y, nodeB.position.x - nodeA.position.x);

if (nodeA.zRotation < 0) {
    nodeA.zRotation = nodeA.zRotation + M_PI * 2;
}

[nodeA runAction:[SKAction rotateToAngle:angle duration:0]];
}

but it only gives this result:

bad rotation

How should I get the sprites to rotate correctly?

All suggestions are appreciated!

EDIT:

I am calling the code above in the init method for the Enemy sprite

-(id)initWithLevel:(int)level andSize:(CGSize)size{
if(self = [super initWithImageNamed:@"alien01"]){
    //position and init stuff

    [self setPosition:self withSeed:seed andSize:size];
    SKNode *center = [[SKNode alloc] init];
    center.position = CGPointMake(self.size.width/2, self.size.height/2);
    [self rotateNode:self toFaceNode:center];
}
return self;
}
1
Where and how do you call this method?ZeMoon
I am calling this method when the enemies are created, and right before I make them run an SKAction to move towards the centerLamikins
Please elaborate with code. I mean to ask which method are you calling it (for instance the update method)ZeMoon
added code in edits aboveLamikins

1 Answers

1
votes

Your problem lies here:

SKNode *center = [[SKNode alloc] init];
center.position = CGPointMake(self.size.width/2, self.size.height/2);
[self rotateNode:self toFaceNode:center];

The center node's position is based on the size of the enemy sprite.

You need to move this part to the scene class. Call the method at the point you initialise the enemy node in the scene. I am assuming the name of the enemy class as EnemySprite and that of the space station node as spaceStation.

EnemySprite *enemy = [[EnemySprite alloc] initWithLevel:1 andSize:CGSizeMake(100, 100)]; //Assuming values as well
[self addChild:enemy];
[self rotateNode:enemy toFaceNode:spaceStation];

This should make it work.