swift - 让 Sprite 缓慢移动到触摸位置

标签 swift xcode sprite-kit

我试图让“玩家” Sprite 缓慢地移动到屏幕上的触摸处。我现在的代码立即将 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. 创建一个将玩家移动到目的地点的 Action 。
  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")
}

关于swift - 让 Sprite 缓慢移动到触摸位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51246822/

相关文章:

ios - 在 Application Loader 中使用 App Store 验证 Assets

ios - SpriteKit : sprite looks blurry (with ghosting) at high velocity but fine at low velocity

ios - 如何检测手指触摸屏幕的时间 iOS

ios - 找不到 Firebase 模块

ios - 在多个 UIView 上添加 Facebook Shimmer

ios - XCUITest 与通知横幅交互。

ios - 在 SpriteKit 项目中使用 Sprite 图集、纹理图集或 Assets 目录

swift - Xcode swift UI 测试对比两张截图

ios - 在 iOS 11.0.3 中插入​​注释 View 失败

swift - 为什么我在 iOS 上从 Swift 调用服务时会收到 SSL 错误?