gpt4 book ai didi

swift - 如何创建左/右移动按钮?

转载 作者:搜寻专家 更新时间:2023-10-31 08:25:52 25 4
gpt4 key购买 nike

请帮忙。我是 Swift 的初学者。我为播放器和左/右按钮添加了 Sprite 。但是我如何为每个按钮添加一个 Action 并将这些 Action 应用到播放器?

import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate {

var player: SKSpriteNode!
var leftMove: SKSpriteNode!
var rightMove: SKSpriteNode!

override func didMoveToView(view: SKView) {

player = SKSpriteNode (imageNamed: "player")

player.position = CGPoint(x:127, y:125)

addChild(player)


leftMove = SKSpriteNode (imageNamed: "leftMove")

leftMove.position = CGPoint(x:80, y:35)

leftMove.size = CGSize (width: 55, height: 55)

addChild(leftMove)


rightMove = SKSpriteNode (imageNamed: "rightMove")

rightMove.position = CGPoint(x:160, y:35)

rightMove.size = CGSize (width: 55, height: 55)

addChild(rightMove)

physicsWorld.contactDelegate = self


}

最佳答案

给按钮一个唯一的名字,比如:

leftMove.name = "Left"
rightMove.name = "Right"

实现touchesBegan中的逻辑:

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

/* Called when a touch begins */
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
let node = self.nodeAtPoint(location)

if (node.name == "Left") {
// Implement your logic for left button touch here:
player.position = CGPoint(x:player.position.x-1, y:player.position.y)
} else if (node.name == "Right") {
// Implement your logic for right button touch here:
player.position = CGPoint(x:player.position.x+1, y:player.position.y)
}
}
}

关于swift - 如何创建左/右移动按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35025126/

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