Sprite-Kit:移动SKSpriteNode

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Sprite-Kit:移动SKSpriteNode相关的知识,希望对你有一定的参考价值。

我知道移动一个物体并不难,但是我的不同,我尝试了各种方式,但没有一个能够工作。

我想要实现什么?

  • 如果用户轻击屏幕的左侧,球将向左移动
  • 如果用户点击屏幕的右侧,则球会向右移动

所以我直接去了touchesBegan并写了以下内容:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        ball?.removeAllActions()
       for touch in touches {

         let moveBY = SKAction.moveTo(x: touch.location(in: view).x, duration: 1.0)
        self.ball?.run(moveBY)
    } 
}

我尝试了四种不同的方式,我无法克服它,也供你参考,这是我的球的信息照片:

info

答案

为了按照您想要的方向移动节点,您首先必须知道三件事

  1. 要移动的节点的anchorPoint
  2. 要移动的节点的父节点的anchorPoint
  3. 要移动的节点的position

节点的anchorPoint属性以从(0,0)到(1,1)的标准化方式存储其值。 SPSpriteNode默认为(0.5,0.5)

节点的position属性将其位置(x,y)坐标存储在正交坐标系中,其中点(0,0)位于PARENT的锚点所在的位置。

所以你的场景的anchorPoint是(0.5,0.5),这意味着如果你在坐标(0,0)处放置一个直接的孩子,那么孩子将被定位,使得它的anchorPoint位于(0,0),它将始终与其父级相匹配anchorPoint

当你使用那些重载touchesBegan,touchesMoved等...在SKSceneSKNodes内部作为一般,如果你想获得在场景(sknode)的所有直接孩子所在的坐标系中表示的触摸位置,你应该做的事情

class GameScene: SKScene {

    override func didMove(to view: SKView) {
        super.didMove(to: view)
        let rect = SKSpriteNode(color: .green, size: CGSize(width: 100, height: 100))
        addChild(rect)
        rect.name = "rect"

        // don't pay attention to these two i need them because i dont have .sks file
        size = CGSize(width: 1334, height: 750)
        anchorPoint = CGPoint(x: 0.5, y: 0.5)
    }

    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard let touch = touches.first else { return }
        let moveAction = SKAction.move(to: touch.location(in: self), duration: 1)
        childNode(withName: "rect")?.run(moveAction)
    }
}

希望它是有帮助的,你可能有的其他问题是你的球不是场景的直接孩子,你得到它的坐标错误

以上是关于Sprite-Kit:移动SKSpriteNode的主要内容,如果未能解决你的问题,请参考以下文章

Sprite-Kit:节点不会向左移动

Xcode 如何自动从其父节点中删除 skspritenode

Sprite-Kit:节点不会向左移动

在我的 Sprite-Kit 游戏中实现这个动作的正确方法是啥?

仅当 SKSpriteNode 是 Fruit 类型时才用手指移动 SKSpriteNode(SKSpriteNode 的子类)

SKSpriteNode 不会移动