在swift Xcode中使用操纵杆移动精灵

时间:2015-09-24 12:11:21

标签: xcode swift sprite-kit

你好:D我的代码如下。

import SpriteKit

class GameScene: SKScene {

    let base = SKSpriteNode(imageNamed: "yellowArt/Base")
    let ball = SKSpriteNode(imageNamed: "yellowArt/Ball")
    let ship = SKSpriteNode(imageNamed: "yellowArt/Ship")

    var stickActive:Bool = false


    override func didMoveToView(view: SKView) {





        self.backgroundColor = SKColor.blackColor()
        self.anchorPoint = CGPointMake(0.5, 0.5)

        self.addChild(base)
        base.position = CGPointMake(0, -200)

        self.addChild(ball)
        ball.position = base.position

        self.addChild(ship)
        ship.position = CGPointMake(0, 200)

        ball.alpha = 0.4
        base.alpha = 0.4
    }




    override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
        for touch in (touches ) {
             let location = touch.locationInNode(self)

            if (CGRectContainsPoint(ball.frame, location)) {
                stickActive = true
            } else {
                stickActive = false
            }
        }
    }

override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) { 

     for touch in (touches ) {

     let location = touch.locationInNode(self)


        if (stickActive == true) {

    let v = CGVector(dx: location.x - base.position.x, dy: location.y - base.position.y)
    let angle = atan2(v.dy, v.dx)

    let deg = angle * CGFloat( 180 / M_PI)
    print( deg + 180 )

        let length: CGFloat = base.frame.size.height / 2

        let xDist: CGFloat = sin(angle - 1.57079633) * length
        let yDist: CGFloat = cos(angle - 1.57079633) * length



        if (CGRectContainsPoint(base.frame, location)) {

            ball.position = location

        } else {

        ball.position = CGPointMake(base.position.x - xDist, base.position.y + yDist)

        ship.zRotation = angle - 1.57079633
        ship.position = CGPointMake(angle, angle)



        }
        } // ends stick active test
    }
    }


    override func touchesEnded(touches: Set<UITouch>, withEvent event: UIEvent?) {
        if (stickActive == true) {
            let move: SKAction = SKAction.moveTo(base.position, duration: 0.2)
            move.timingMode = .EaseOut
            ball.runAction(move)
    }
    }


    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}

上面的代码创建了一个操纵杆和一艘船。通过移动操纵杆,我可以用操纵杆旋转“船”。但是我想让船沿着操纵杆所朝的方向移动。我该如何解决这个问题?谢谢。

1 个答案:

答案 0 :(得分:3)

由于你有items,你的船不会去任何地方只要你移动操纵杆,船就会去那一点 - 移开那条线。

我会使用ship.position = CGPointMake(angle, angle).方法来移动船只。首先,你需要找到你想要在x和y方向上移动多少。 在update语句下面为操纵杆移动创建类变量:

var stickActive:Bool = false

将以下代码放入var xJoystickDelta = CGFloat() var yJoystickDelta = CGFloat() 方法中:

touchesMoved

将以下代码放入xJoystickDelta = location.x - base.position.x yJoystickDelta = location.y - base.position.y 方法中:

update

我希望这会有所帮助。