【问题标题】:SKShpapeNode position and touch.location differenceSKShpapeNode 位置和 touch.location 的区别
【发布时间】:2017-01-30 22:46:51
【问题描述】:

我正在学习 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)")
        }
    }

【问题讨论】:

    标签: ios swift sknode


    【解决方案1】:

    尝试做这样的事情

    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)
            }
        }
    }
    
    }
    

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

    【讨论】:

    • 当我尝试这个时,我触摸的位置和 skspritenode 位置设置在不同的位置。例如。当我触摸点是(10,-20)时,skspritenode 定位不同的位置。当我单击该 sksprite 节点时,该位置不同。如何解决这个问题。我的需要是当我单击单个位置 sksprite 节点时,定位在该点上
    猜你喜欢
    • 2013-10-30
    • 1970-01-01
    • 1970-01-01
    • 2014-07-30
    • 1970-01-01
    • 2021-11-18
    • 2011-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多