限制我的玩家在x方向移动很多
问题描述:
在图片中,您可以在我的游戏中看到我的船。我已经做到了,它不能在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)
}
}
答
你计算你的未来船的位置,你也可以检查x
是否在您指定的范围内,在moveNodeToLocation
:
let newPosition = boat.position.x + dx
if newPosition > 20 && newPosition < 300 {
boat.position = CGPoint(x: newPosition, y: -300)
}
这里的极限值仅为举例来说,如果需要的话,你可以动态地计算,当然他们,想象bgTexture.size
将在这里有用,甚至可以通过水平等
表现出一定的代码不同,它是简单的事你想要做什么,但至少给一些代码来使用 – DevB2F
现在,我将我的代码添加到文本! – Flinigan