gpt4 book ai didi

swift - 我的 Sprite 不执行我告诉它的操作?

转载 作者:行者123 更新时间:2023-11-28 16:05:54 24 4
gpt4 key购买 nike

我正在使用 Swift 和 SpriteKit 在 Xcode 7 中制作一个应用程序。我的想法是拥有一艘随手指移动的宇宙飞船,或者基本上只是跟随它,但我遇到了麻烦。这是代码:

import Foundation
import SpriteKit

class secondScene: SKScene {

override func didMoveToView(view: SKView) {

// var timer = NSTimer.scheduledTimerWithTimeInterval(0.2, target: self, selector: Selector(spawnBullets()), userInfo: nil, repeats: true)

//buttons
let leftbutton = SKSpriteNode(imageNamed: "LeftArrow")
leftbutton.position = CGPoint(x: self.frame.size.width*0.2, y: self.frame.size.height*0.1)
leftbutton.size = CGSize(width: 220, height: 80)
leftbutton.color = SKColor.blueColor()
leftbutton.zPosition = 100
self.addChild(leftbutton)

let rightbutton = SKSpriteNode(imageNamed: "RightArrow")
rightbutton.position = CGPoint(x: self.frame.size.width*0.8, y: self.frame.size.height*0.1)
rightbutton.size = CGSize(width: 220, height: 80)
rightbutton.color = SKColor.blueColor()
rightbutton.zPosition = 100
self.addChild(rightbutton)

//spaceship
let spaceship = SKSpriteNode(imageNamed: "spaceship")
spaceship.zPosition = 100
spaceship.size = CGSize(width: 200, height: 120)
spaceship.position = CGPoint(x: self.frame.size.width/2, y: self.frame.size.height*0.15)
self.addChild(spaceship)
}

let spaceship = SKSpriteNode(imageNamed: "spaceship")

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

for touch: AnyObject in touches {
let location = touch.locationInNode(self)
spaceship.position.x = location.x
}
}
}

我运行此程序,在我看来我的宇宙飞船似乎应该跟随我的手指,但事实并非如此。它只是停留在我之前指定的位置。我没有错误,我没有想法。有什么想法吗?

最佳答案

在 didMoveToView 的飞船代码中删除这一行

let spaceship = SKSpriteNode(imageNamed: "spaceship")

这样您实际上是在使用您在 touchesBegan 上面创建的全局属性。

您可能还想在 touchesMoved 中包含/移动您的代码。

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

for touch in touches {
let location = touch.locationInNode(self)

spaceship.position.x = location.x
}
}

希望对你有帮助

关于swift - 我的 Sprite 不执行我告诉它的操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40291614/

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