精灵跟着触摸

时间:2015-03-29 03:37:40

标签: swift sprite-kit

当我触摸屏幕时,我正试图让一个精灵跟随我的手指。我已经四处寻找并发现了一些有效的东西,但这对于这个过程来说似乎有点多了;我也是初学者,所以我也不确定这是不是最好的。

let player = SKSpriteNode(imageNamed: "Player")

var location = CGPoint(x: 0, y: 0)
var touched: CGPoint? = nil

override func didMoveToView(view: SKView) {
    backgroundColor = SKColor.whiteColor()

    player.position = CGPoint(x: size.width * 0.5, y: size.height * 0.25)

    addChild(player)

    runAction(SKAction.repeatActionForever(
        SKAction.sequence([
            SKAction.runBlock(addEnemy),
            SKAction.waitForDuration(0.25)
            ])
        ))
}

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

touched = true
for touch: AnyObject in touches {
    location = touch.locationInNode(self)
}
}

override func touchesMoved(touches: NSSet, withEvent event: UIEvent) {

for touch: AnyObject in touches {
    location = touch.locationInNode(self)
}
}

override func touchesEnded(touches: NSSet, withEvent event: UIEvent) {
// Stop node from moving to touch
touched = false
}

override func update(currentTime: NSTimeInterval) {

if (touched) {
    moveNodeToLocation()
}
}

// Move the node to the location of the touch
func moveNodeToLocation() {
// How fast to move the node
let speed = 1 as CGFloat
// Compute vector components in direction of the touch
var dx = location.x - player.position.x
var dy = location.y - player.position.y
let mag = sqrt(dx*dx+dy*dy)
// Normalize and scale
dx = dx/mag * speed
dy = dy/mag * speed
player.position = CGPointMake(player.position.x+dx, player.position.y+dy)

}

0 个答案:

没有答案