swift - 如何在 spritekit 中通过触摸将 Sprite 相对于其原始位置移动

标签 swift sprite-kit sprite

我希望相对于玩家的触摸来移动 Sprite 。我熟悉 moveTo SKActions,但是我想知道如何实现 Sprite 移动,其中 Sprite 随着用户的触摸移动而移动。

例如,我在屏幕中央有一个 Sprite 。如果我触摸屏幕底部并向上移动手指, Sprite 将从中心向上移动(它的原始位置)。

谢谢!

最佳答案

试试这个:

import SpriteKit

class GameScene: SKScene {

    var node = SKSpriteNode()
    var nodePosition = CGPoint()
    var startTouch = CGPoint()


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

        // node set up
        node = SKSpriteNode(color: .red, size: CGSize(width: 50, height: 50))
        node.position = CGPoint.zero
        self.addChild(node)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        if let location = touch?.location(in: self){
            startTouch = location
            nodePosition = node.position
        }
    }
    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
        let touch = touches.first
        if let location = touch?.location(in: self){
            node.run(SKAction.move(to: CGPoint(x:  nodePosition.x + location.x - startTouch.x, y: nodePosition.y + location.y - startTouch.y), duration: 0.1))
        }
    }

}

关于swift - 如何在 spritekit 中通过触摸将 Sprite 相对于其原始位置移动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49781837/

相关文章:

json - Marvel API Swift4 JSON 解码

ios - 使节点动态仅适用于一个对象 Swift 和 Spritekit

python - 如何让 Sprite 在 Pygame 和 Python 中的所有计算机上均匀移动

c++ - DX11 Sprite 问题

ios - swift 太聪明?使用 XCTest 测试时检查对象类型

ios - UITableViewCell 自定义按钮图像未在 Swift 3 中更新

ios - 最初从 firebase 获取无效的推送 token ,最后获取有效的推送 token

ios - 如何以编程方式设置 ARSKView 场景中 SKNode 的位置?

ios - Swift 4.2 - 类型 '(____) -> () -> (____)' 的值没有成员 'childNode'

css - 使用 msbuild 创建 CSS Sprite ?