Ruan33
Ruan33

Reputation: 29

How to rotate something using spritekit relative to user touch coordinates

I want to rotate a gun based on the user dragging their finger on the screen. I figure i will need my cartesian points in polar coordinates and that i will need a long press gesture which is both things that i have. I am just wondering how i would go about programming this? sorry i'm really new to sprite kit i have read all of apple's documentation and i'm having a hard time finding this. My anchor point is 0,0.

-(void)shootBullets:(UILongPressGestureRecognizer *) gestureRecognizer
{
    double radius;
    double angle;
      SKSpriteNode *gun = [self newGun];
 }

i figured out how to get the angle but now my zrotation wont work. Like i nslog and the angles are right but when i click gun.zrotation and i tap nothing happens? please help i'm getting uber mad.

-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
UITouch *touch = [[event allTouches] anyObject];
CGPoint location = [touch locationInView:touch.view];
SKSpriteNode *gun = [self newGun];
self.gunRotation = atanf(location.y/location.x)/0.0174532925;
gun.zRotation = self.gunRotation;
NSLog(@"%f",gun.zRotation);
}

Upvotes: 2

Views: 2102

Answers (2)

bmeyer
bmeyer

Reputation: 56

This is a very old question, but here is what I did - hopefully it will help someone out there:

#import "MyScene.h"
#define SK_DEGREES_TO_RADIANS(__ANGLE__) ((__ANGLE__) * 0.01745329252f) // PI / 180

Then add this:

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    for (UITouch *touch in touches) {
        CGPoint positionInScene = [touch locationInNode:self];

        float deltaX = positionInScene.x - gun.position.x;
        float deltaY = positionInScene.y - gun.position.y;

        float angle = atan2f(deltaY, deltaX);

        gun.zRotation = angle - SK_DEGREES_TO_RADIANS(90.0f);  
    }
}

Upvotes: 4

Alex Stone
Alex Stone

Reputation: 47328

Check out the answers I got to this question about how to implement a rotary knob, people have already figured out all the geometry, all you need to do is implement a transparent rotary knob, get its angle and pass it to your sprite kit object, using action rotate

Upvotes: 0

Related Questions