0

I'm trying to use UIGestureRecognizers to be able to move a sprite around within a SpriteKit scene. So far it moves around just fine, but it stops as soon as I take my finger off the screen. What I want to do now is translate the gesture end into a flicking style motion onto the sprite so it continues in the direction I was moving my finger with a degree of force based on that movement.

Here's what I have this far which seems to work for horizontal movements, but keeps sending the sprite in the wrong direction on the Y axis.

if (recognizer.state == UIGestureRecognizerStateEnded) {
    CGPoint velocity = [recognizer velocityInView:self.view];
    velocity = [self convertPointFromView:velocity];

    [touchedNode.physicsBody applyForce:CGVectorMake(velocity.x, velocity.y)];
}

Update - A little more about what happens when I swipe currently. The effect produced by a pan and release results in the sprite travelling in the correct direction, but with a downward angle added to it. A swipe down results in an upward motion of travel and upward swipe results in a downward motion of travel.

Update 2 - It may be that this code is too simple for what I want to achieve and I should be calculating how far the sprite should move before applying the force so I can give it a specific velocity vector based on its movements?

Mark Reid
  • 2,611
  • 3
  • 23
  • 45

2 Answers2

0

I just solve this problem by this way(swift):

let transformerX = 1024/self.view!.frame.size.with
let transformerY = 768/self.view!.frame.size.height

if (recognizer.state == .ended) {
    let velocity = recognizer.velocity(InView:self.view)
    touchedNode.physicsBody?.applyForce:CGVector(dx:velocity.x* transformerX, dy: velocity.y* transformerY)
}

I do not know why this way works,just find it by accident. But it really works in any size of view.

Prasad
  • 1,562
  • 5
  • 26
  • 40
0
let transformerX = 1024/self.view!.frame.size.width
let transformerY = 768/self.view!.frame.size.height
if (recognizer.state == .ended) { 
   let velocity = recognizer.velocity(InView:self.view) 
   touchedNode.physicsBody?.applyForce:CGVector(dx:velocity.x* transformerX, dy: velocity.y* transformerY) 
}
slfan
  • 8,950
  • 115
  • 65
  • 78