首页 > 解决方案 > 在某个位置画一个十字以及节点旋转的工作原理

问题描述

我正在使用 spriteKit 来创建一个小游戏,但在我触摸屏幕的地方试图画一个十字(比如和 X)时却被阻止了。因为我想在旋转两个矩形时画一个 XI 思想,一个是 Pi/4,另一个是 -Pi/4。

我有以下代码,我一直在玩节点位置,在两个轴上添加 10 或 20px。但我无法理解矩形如何在它们的中心相交以创建一个十字(如 X)。

这就是我的代码:

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?)
    {
        guard let touch = touches.first
            else
        {
            return
        }

    let location = touch.location(in: self)

    let touchedNode = nodes(at: location)
    _ = atPoint(location).name

    print("Posición touch: \(touchedNode)")

    // Draw the cross in the touched point
    let redSprite1 = SKShapeNode(rect: CGRect(x: 0, y: 0, width: 10, height: 40))
    redSprite1.fillColor = .green
    redSprite1.position = CGPoint(x: location.x - 10.0, y: location.y)
    redSprite1.zRotation = CGFloat(-Pi/4)
    addChild(redSprite1)
//      2
        let redSprite2 = SKShapeNode(rect: CGRect(x: 0, y: 0, width: 10, height: 40))
        redSprite2.fillColor = .red
        redSprite2.position = CGPoint(x: location.x + 10.0, y: location.y)
        redSprite2.zRotation = CGFloat(Pi/4)
        addChild(redSprite2)
    }

我注意到旋转不是从形状的中心而是在它们的底部进行的。是否有任何选项可以从中心旋转形状或瓷砖?

标签: iosmathsprite-kitskspritenode

解决方案


感谢@bg2b 的解决方案。

查看在@bg2b 答案上链接并应用的苹果文档,给出以下代码。

// 1
let redSprite1 = SKShapeNode(rectOf: CGSize(width: 10.0, height: 40.0))
redSprite1.fillColor = .green
redSprite1.position = CGPoint(x: location.x, y: location.y)
redSprite1.zRotation = CGFloat(-Pi/4)
redSprite1.name = "cruz1"
addChild(redSprite1)
// 2
let redSprite2 = SKShapeNode(rectOf: CGSize(width: 10.0, height: 40.0))
redSprite2.fillColor = .red
redSprite2.position = CGPoint(x: location.x, y: location.y)
redSprite2.zRotation = CGFloat(Pi/4)
redSprite2.name = "cruz2"
addChild(redSprite2)

推荐阅读