让精灵缓慢移向触摸

时间:2018-07-09 13:31:14

标签: swift xcode sprite-kit

我正在尝试让“玩家”精灵朝屏幕上的触摸缓慢移动。我现在拥有的代码将sprite立即移动到屏幕上发生触摸的位置。这是我当前的代码。谢谢!

    //
//  GameScene.swift
//  testing
//
//  Created by Matthew Jahnes on 7/3/18.
//  Copyright © 2018 Matthew Jahnes. All rights reserved.
//

import SpriteKit
import GameplayKit

class GameScene: SKScene {

    var player = SKSpriteNode()


    override func didMove(to view: SKView) {
        self.anchorPoint = CGPoint(x:0.5, y:0.5)


        player = SKSpriteNode(color: UIColor.red, size: CGSize(width: 90, height:90))
        player.position = CGPoint(x:0, y:0)
        self.addChild(player)


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

    for touch in touches {
        let location = touch.location(in: self)

        player.position.x = location.x
        player.position.y = location.y

    }
}


override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered
}

}

1 个答案:

答案 0 :(得分:0)

您需要

  1. 创建用于将播放器移动到目标点的动作。
  2. 停止上一个move操作(如果存在)
  3. 运行新的move操作

这是代码

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    guard let touch = touches.first else { return }
    let destination = touch.location(in: self)
    let move = SKAction.move(to: destination, duration: 2)
    player.removeAction(forKey: "move")
    player.run(move, withKey: "move")
}