Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rotate a sprite to sprite position not exact in SpriteKit with Swift

I'm trying to rotate a player to the touch. Using the touches move function, I set the location to a variable. I then call a function. It works but the angle is off. Location is the global variable and player is the sprite I want to turn. It's off by about 15 degrees.

   func rotatePlayer(){

     let angle = atan2(location!.y - player!.position.y , location!.x - player!.position.x)
    player?.zRotation = angle
}
like image 798
paralaxbison Avatar asked Nov 09 '22 00:11

paralaxbison


2 Answers

According to the SpriteKit Best Practices doc

Use game logic and art assets that match SpriteKit’s coordinate and rotation conventions. This means orienting artwork to the right. If you orient the artwork in some other direction, you need to convert angles between the conventions used by the art and the conventions used by SpriteKit.

Since the default spaceship points upward (when zRotation is 0), you will need to offset your angle by 90 degrees (pi/2 radians) so that the ship faces to the right when zRotation is zero:

player?.zRotation = angle - CGFloat(M_PI_2)

Alternatively, you can rotate the spaceship to the right. To rotate the image, click on Assets.xcassets and then click on Spaceship. Right click on the Spaceship image and select the Open in External Editor menu item. This will open the image in the Preview app. In Preview, select Tools > Rotate Right and quit Preview. By rotating the artwork, your code should work without any changes.

like image 83
0x141E Avatar answered Dec 26 '22 14:12

0x141E


Try something like this

//set sprite to image



Person = SKSpriteNode(imageNamed: "Person")




    //set size
    Person.size = CGSize(width: 40, height: 7)



    //set position
    Person.position = CGPoint(x: self.frame.width / 2, y: self.frame.height / 2 + 120)





    //rotate node 3.14 / 2 = to 90 degree angle
    Person.zRotation = 3.14 / 2



    Person.zPosition = 2.0
like image 25
BOB Avatar answered Dec 26 '22 13:12

BOB