gpt4 book ai didi

swift - 限制我的玩家在 x 方向移动太多

转载 作者:行者123 更新时间:2023-11-30 12:32:28 25 4
gpt4 key购买 nike

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

这是游戏的图片:

/image/0e1ZX.png

类游戏场景: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)
}

}

最佳答案

您可以计算船的 future 位置,以便还可以检查 x 是否在您在 moveNodeToLocation 中指定的范围内:

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

这里的限制值仅作为示例,当然如果需要,您可以动态计算它们,想象一下bgTexture.size在这里会很有用,甚至可能会因级别等而异

关于swift - 限制我的玩家在 x 方向移动太多,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43332558/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com