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

后端 未结 3 1912
生来不讨喜
生来不讨喜 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:40

    You could do something like this.

    -(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
        touchOn=YES;
        UITouch *touch = [touches anyObject];
        CGPoint location = [touch locationInNode:self.parent];
        touchPos =location;
        [self.physicsBody setVelocity:CGVectorMake(0, 0)];
    
    }
    -(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event {
        touchOn=YES;
        UITouch *touch = [touches anyObject];
        CGPoint location = [touch locationInNode:self.parent];
        touchPos =location;
    }
    -(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event {
        touchOn=NO;
    }
    -(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event {
        touchOn=NO;
    }
    -(void)update:(NSTimeInterval)dt {
        if (touchOn) {
            CGVector vector = CGVectorMake((touchPos.x-self.position.x)/dt, (touchPos.y-self.position.y)/dt);
            self.physicsBody.velocity=vector;
        }
    }
    

    Subclass a node and make a method called update that receives updates from the scene along with the change in time. Also add touches methods and keep track of the current touch position.

提交回复
热议问题