SpriteKit根据操纵杆的角度改变精灵

时间:2017-11-01 15:06:13

标签: ios swift sprite-kit joystick

我使用此代码在SpriteKit游戏中创建了一个虚拟操纵杆。我的所有其他节点(如播放器播放的地图和场景设置等)是SKNode,worldNode的子节点,除了我的操纵杆和播放器。因此,移动worldNode会在场景中移动角色,同时保持摄像机以角色为中心。

DPad = SKSpriteNode(imageNamed: "dpad")
DPad.size = CGSize(width: 150, height: 150)
DPad.position = CGPoint(x: -270, y: -100)

DPad.zRotation = -1.0

thumbNode = SKSpriteNode(imageNamed: "joystick")
thumbNode.size = CGSize(width: 50, height: 50)
thumbNode.position = CGPoint(x: DPad.position.x, y: DPad.position.y)

self.addChild(DPad)
self.addChild(thumbNode)


//TOUCHES METHOD 

for touch in touches {
        let location = touch.location(in: self)
        if isTracking == true {

            let v = CGVector(dx: location.x - DPad.position.x, dy: location.y - DPad.position.y)
            let angle = atan2(v.dy, v.dx)
            let deg = angle * CGFloat(180 / Double.pi)

            let Length:CGFloat = DPad.frame.size.height / 2 - 20
            let xDist: CGFloat = sin(angle - 1.57079633) * Length
            let yDist: CGFloat = cos(angle - 1.57079633) * Length

            xJoystickDelta = location.x - DPad.position.x
            yJoystickDelta = location.y - DPad.position.y

            thumbNode.position = CGPoint(x: DPad.position.x - xDist, y: DPad.position.y + yDist)



            if DPad.contains(location) {
                thumbNode.position = location
            }else {
                thumbNode.position = CGPoint(x: DPad.position.x - xDist, y: DPad.position.y + yDist)
            }

        }
    }

//UPDATE METHOD 

override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered
    let xScale = CGFloat(0.06) //adjust to your preference
    let yScale = CGFloat(0.06) //adjust to your preference

    //xJoystickDelta and yJoystickDelta are CGFloats declared at the top of my scene
    let xAdd = xScale * self.xJoystickDelta
    let yAdd = yScale * self.yJoystickDelta

    worldNode.position.x -= xAdd
    worldNode.position.y -= yAdd

}

我的操纵杆没有像我想要的那样跟踪,根据拇指节点位于下图中四个标记部分的位置,以交叉方式跟踪我的角色精灵

img1

使用上面的代码,如何更改十字的跟踪,以便我的角色的精灵根据拇指节点在下图中X的四个部分内的位置而改变。

img2

(我为可怕的图像质量道歉,我很快就把它们掀起来问这个问题)

0 个答案:

没有答案