0

I'm making two games and for both I want to know how I can find an angle from a swipe. I've heard you use UIPanGesutre but I don't know how to use it. Any help?

sangony
  • 11,426
  • 4
  • 34
  • 51

2 Answers2

0

You can detect the start and stop location coordinates of the touch and calculate the angle with the two points.

sangony
  • 11,426
  • 4
  • 34
  • 51
0

Within the touchesBegan event, determine the touch location:

Create an instance variable called initialLocation of type CGPoint in your interface

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
    //Determine touch location and store in instance variable (so you can use it again in touchesEnded)
    UITouch *touch = [touches anyObject];
    initialLocation = [touch locationInNode:self];
}

- (void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event{
    //Determine touch location
    UITouch *touch = [touches anyObject];
    CGPoint finalLocation = [touch locationInNode:self];

    //Find change in x and y between the touches
    CGFloat changeX = finalLocation.x - initialLocation.x;
    CGFloat changeY = finalLocation.y - initialLocation.y;

    //Use trig to find angle (note this angle is in radians)
    float radians = atan(changeY/changeX);

    //Convert to degrees
    float degrees = 360 * radians/(2 * M_PI);

    //*Note* you would have to alter this part depending on where you are measuring your angle from (I am using the standard counterclockwise from right)
    //This step is due to the limitation of the atan function
    float angle;
    if (changeX > 0 && changeY > 0){
        angle = degrees;
    }
    else if (changeX < 0 && changeY > 0){
        angle = 180 + degrees;
    }
    else if (changeX < 0 && changeY < 0){
        angle = 180 + degrees;
    }
    else{
        angle = 360 + degrees;
    }
    NSLog(@"Now: %f",angle);
    //^^^ HERE IS THE ANGLE! ^^^

}

I hope this helps!

  • It kinda worked. When I was swiping to the right, sometimes it said 360 degrees, and sometimes it said about 0. – Young_Programmer Mar 13 '15 at 00:01
  • Actually, when I swiped on the top half it printed 0, but the bottom half printed around 360 – Young_Programmer Mar 13 '15 at 00:02
  • Yea, that makes sense. This image explains the angles in calculus if you are unfamiliar with it: http://upload.wikimedia.org/wikipedia/commons/thumb/1/13/Polar_graph_paper.svg/2000px-Polar_graph_paper.svg.png – Luigi Mangione Mar 14 '15 at 00:58