How to hit objects with finger movement in Sprite Kit, Objective C

后端 未结 3 1896
生来不讨喜
生来不讨喜 2021-01-03 12:13

I\'m trying to make a game in which I have some SKSpriteNodes and the User can hit them with finger movement, I\'m using apple\'s new Sprite Kit.

To

3条回答
  •  一生所求
    2021-01-03 12:21

    Haven't had time to actually run this but how about something like this: don't bother with putting a node X like described above, rather:

    In touchesBegan, keep track of the time and position of the touch

    - (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
    {
        UITouch *touch = [touches anyObject];
        CGPoint location = [touch locationInNode:self];
    
        //store location of first touch
        self.firstTouch = location;
    
        //get time
        self.startTouch = [NSDate date];
    }
    

    In touchesMoved, check if you have touched any of the nodes, If so, work out the angle and speed based on the start and end positions of the touch and then apply velocity to the impacted node?

    - (void) touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        UITouch *touch = [touches anyObject];
        CGPoint location = [touch locationInNode:self];
        SKNode *node = [self nodeAtPoint:location];
    
        //if you've touched one of your nodes
        if ([node.name isEqualToString:@"whateverNode"]) {
         //work out time between touches
         NSTimeInterval timeBetween = [[NSDate date] timeIntervalSinceDate:self.startTouch];
    
         //work out angle between touches (if you want to send the impacted node in that direction)
         float angle = atan2f (location.y - self.firstTouch.y, location.x - self.firstTouch.y) ;
    
         //apply to node
         CGFloat thrust = 0.01/timeBetween; 
    
         CGPoint thrustVector = CGPointMake(thrust*cosf(angle),
                   thrust*sinf(angle));
         [node.physicsBody applyTorque:thrustVector];
        }
    }
    

    Note the physics bit at the end could be (completely) incorrect.

提交回复
热议问题