2017-04-10 38 views
0

在圖片中,您可以在我的遊戲中看到我的船。我已經做到了,它不能在y方向移動,只能在x方向移動。現在,我想限制船隻,使它不能移出水面,而不是現在它可以移動整個屏幕寬度的地方。我怎樣才能使這成爲可能?限制我的玩家在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) 
} 

}

+0

表現出一定的代碼不同,它是簡單的事你想要做什麼,但至少給一些代碼來使用 – DevB2F

+0

現在,我將我的代碼添加到文本! – Flinigan

回答

0

你計算你的未來船的位置,你也可以檢查x是否在您指定的範圍內,在moveNodeToLocation

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

這裏的極限值僅爲舉例來說,如果需要的話,你可以動態地計算,當然他們,想象bgTexture.size將在這裏有用,甚至可以通過水平等