限制我的玩家在x方向移动很多

时间:2017-04-10 20:41:46

标签: swift width coordinates skspritenode

在图像中,您可以在我的游戏中看到我的船。我已经做到了它不能在y方向上移动,只能在x方向上移动。现在,我想限制船只,使它不能移出水面,而不是现在它可以移动屏幕的整个宽度。我怎样才能做到这一点?

以下是游戏的图片:

https://i.stack.imgur.com/0e1ZX.png

类GameScene:SKScene {

var boat = SKSpriteNode()

var bg = SKSpriteNode()

var touched:Bool = false

var location = CGPoint.zero




override func didMove(to view: SKView) {


    boat.position = CGPoint(x:0, y:0)

    self.addChild(boat)

    let bgTexture = SKTexture(imageNamed: "bg.png")

    let moveBGAnimation = SKAction.move(by: CGVector(dx: 0, dy: -bgTexture.size().width), duration: 5)
    let shiftBGAnimation = SKAction.move(by: CGVector(dx: 0, dy: bgTexture.size().width), duration: 0)
    let moveBGForever = SKAction.repeatForever(SKAction.sequence([moveBGAnimation, shiftBGAnimation]))


    var i: CGFloat = 0


    while i < 3 {

        bg = SKSpriteNode(texture: bgTexture)

        bg.position = CGPoint(x: self.frame.midX, y: bgTexture.size().width * i)

        bg.size.height = self.frame.height

        bg.run(moveBGForever)

        self.addChild(bg)

        i += 1

        bg.zPosition = -1
    }


    let boatTexture = SKTexture(imageNamed: "boat.png")

    boat = SKSpriteNode(texture: boatTexture)

    boat.position = CGPoint(x: self.frame.midX, y: self.frame.midY - 300)

    boat.physicsBody = SKPhysicsBody(circleOfRadius: boatTexture.size().height / 2)

    boat.physicsBody!.isDynamic = false

    self.addChild(boat)

}


override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {

    touched = true
    for touch in touches {
    location = touch.location(in:self)

    }
}


override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {

    touched = false


}


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

    for touch in touches {
        location = touch.location(in: self)
    }
}



override func update(_ currentTime: TimeInterval) {
    // Called before each frame is rendered

    if (touched) {
        moveNodeToLocation()
    }
}

func moveNodeToLocation() {
    // Compute vector components in direction of the touch
    var dx = location.x - boat.position.x
    // How fast to move the node. Adjust this as needed
    let speed:CGFloat = 0.25
    // Scale vector
    dx = dx * speed
    boat.position = CGPoint(x:boat.position.x+dx, y: -300)
}

}

1 个答案:

答案 0 :(得分:0)

您可以计算船只的未来位置,这样您也可以在x中检查moveNodeToLocation是否在您指定的范围内:

let newPosition = boat.position.x + dx
if newPosition > 20 && newPosition < 300 {
    boat.position = CGPoint(x: newPosition, y: -300)
}

此处的限制值仅作为示例,您可以根据需要动态计算它们,想象bgTexture.size在这里很有用,甚至可能因级别而异等。