当我触摸物体时,如何停止移动物体?

时间:2016-02-19 19:54:41

标签: ios swift sprite-kit touchesbegan

我的游戏应用程序有随机移动的对象。当我触摸/抓住它时,我想停止并在屏幕上打印一些单词。但我不知道在gamescene.swift页面中我能做什么。我应该在touchesBegan中写些什么?这是我的代码:

import SpriteKit

let BallCategoryName = "ball"

class GameScene: SKScene {
   override func didMoveToView(view: SKView) {
       super.didMoveToView(view)

       let borderBody = SKPhysicsBody(edgeLoopFromRect: self.frame)


       borderBody.friction = 0


       self.physicsBody = borderBody


       physicsWorld.gravity = CGVectorMake(15, 15)

       let ball = childNodeWithName(BallCategoryName) as! SKSpriteNode
       ball.physicsBody!.applyImpulse(CGVectorMake(10, -10))

 }
    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {

       let touch = touches.first as! UITouch


        }

}

1 个答案:

答案 0 :(得分:0)

首先,您需要将变量球放在didMoveToView:

之外
class GameScene: SKScene {

    let ball = childNodeWithName(BallCategoryName) as! SKSpriteNode

    override func didMoveToView(view: SKView) {
        [...]
    }
}

的touchesBegan:

override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
    for touch:AnyObject in touches{
        let location = (touch as! UITouch).locationInNode(self)
        let nodeTouched = nodeAtPoint(location)

        //Detect if the ball is touched
        if(nodeTouched == ball){
            //Do something
        }
    }
}