ios - SKShapeNode 位置和 touch.location 的区别

标签 ios swift sknode

我在学习 Swift 中的 SKNodes 时遇到了一个问题。应用程序应该非常简单:触摸屏并让节点出现在触摸的位置。我不知道为什么,但矩形一直显示在屏幕上的不同位置,但 sn.positiontouch.location(in: view) 位置相同。怎么了?

import SpriteKit
import GameplayKit

class GameScene: SKScene {

    private var spinnyNode : SKShapeNode?
    private var touchPoint : CGPoint!

    override func didMove(to view: SKView) {

        let size = CGSize(width: 50, height: 50)

        spinnyNode = SKShapeNode(rectOf: size, cornerRadius: CGFloat(0.6)) //init

        if let spinnyNode = self.spinnyNode{

            spinnyNode.lineWidth = 3

            let rotate = SKAction.repeatForever(SKAction.rotate(byAngle: CGFloat(M_PI), duration: 1))
            let fade = SKAction.fadeOut(withDuration: 0.5)
            let remove = SKAction.removeFromParent()

            spinnyNode.run(rotate)
            spinnyNode.run(SKAction.sequence([fade, remove]))

        }
    }

    func touchDown(point pos : CGPoint){
        if let sn = self.spinnyNode?.copy() as! SKShapeNode? {

            sn.position = CGPoint(x: touchPoint.x , y: touchPoint.y)
            print("touchDown x:\(touchPoint.x), y:\(touchPoint.y)")

            self.addChild(sn)
        }
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard touches.count == 1 else{
            return
        }
        if let touch = touches.first{
            touchPoint = touch.location(in: view)

            touchDown(point: touchPoint)
            print("touchesBegan -> x: \(touchPoint.x) y: \(touchPoint.y)")
        }
    }

最佳答案

尝试做这样的事情

import SpriteKit
import GameplayKit

class GameScene: SKScene {

//use whichever image for your node
var ballNode = SKSpriteNode(imageNamed: "ball")

var fingerLocation = CGPoint()

override func didMove(to view: SKView) {

    ballNode.size = CGSize(width: 100, height: 100)
    ballNode.position = CGPoint(x: self.size.width*0.5, y: self.size.height*0.5)

}


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


    if let location = touches.first?.location(in: self){

        if let copy = ballNode.copy() as? SKSpriteNode {
            copy.position = location
            addChild(copy)
        }
    }
}

}

每次我点击一个随机点,球就会出现。希望这会有所帮助。

关于ios - SKShapeNode 位置和 touch.location 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41946773/

相关文章:

ios - Swift:将 SKshapeNode 定位到最左/最右但不在屏幕外

swift - 整洁、干净地访问 SKNode

iOS:后台/前台事件

ios - 解析动态 JSON 的模型

ios - 升级到 Swift 3 错误 - ld : framework not found GoogleInterchangeUtilities

swift - 在 Swift 中按键分组字典

ios - Swift + Objective C Venmo Pod : 'VENUser.h' file not found

swift - 漏洞 : hit-testing with sibling nodes and the userInteractionEnabled property in Sprite Kit

javascript - 更改 HTML5 视频元素源后立即查找的问题

ios - 如何根据 iDevice 精确测量 Swift 节点的大小和位置