gpt4 book ai didi

ios - 长按结束 swift sprite kit 时如何运行函数

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

我正在运行一个非常简单的代码,我试图检测长按何时结束,然后执行一个函数,但我似乎无法弄清楚该怎么做。我已经在网上查看了很多资源,但一直无法弄清楚。我对使用 Swift 进行编码非常陌生,所以如果答案很简单,我会提前致歉。这是所有代码:

import SpriteKit

class GameScene: SKScene {

let char = SKSpriteNode(imageNamed: "flying character")

override func didMove(to view: SKView) {
setScene()
}

@objc func press() {
physicsWorld.gravity = CGVector(dx: 0.1, dy: 1.5)
if UILongPressGestureRecognizer.State.changed == .ended {
print ("the gesture has ended")
}
}

func setScene() {
backgroundColor = UIColor(red: 255/255, green: 255/255, blue: 221/255, alpha: 1.0)
char.size = CGSize(width: frame.size.width/5, height: frame.size.width/5)
char.run(SKAction.rotate(byAngle: .pi*11/6, duration: 0.00001))
char.position = CGPoint(x: frame.midX - 100, y: frame.midY + 150)
addChild(char)
char.physicsBody = SKPhysicsBody(circleOfRadius: char.size.width/2)
char.physicsBody?.categoryBitMask = PhysicsCategories.charCategory
physicsWorld.gravity = CGVector(dx: 0.1, dy: -1.5)
char.physicsBody?.affectedByGravity = true
view?.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(press)))
}
}

如您所见,我只是在长按结束时尝试执行打印命令。

最佳答案

首先,您可能会注意到一个非常重要的事情是您的问题与 SpriteKit 本身无关!您正在使用 UILongPressGestureRecognizer,它是 UIKit 中的一个类! Apple Docs

另外,请注意您正在将手势应用到整个 View 。因为我假设这是一个角色会飞的游戏,所以我想这种行为是预期的。

我想您面临的问题是您没有使用分配给您的 View 的 UILongPressGestureRecognizer!相反,您正在访问 UILongPressGestureRecognizer 类属性/方法。更多详情可以浏览this section of the Swift documentation


一个快速解决你问题的方法是改变你的新闻功能

@objc func press() {
physicsWorld.gravity = CGVector(dx: 0.1, dy: 1.5)
if UILongPressGestureRecognizer.State.changed == .ended {
print ("the gesture has ended")
}
}

@objc func press(_ gestureRecognizer: UILongPressGestureRecognizer) {
physicsWorld.gravity = CGVector(dx: 0.1, dy: 1.5)
if gestureRecognizer.state == .ended {
print ("the gesture has ended")
}
}

和你的 setScene 函数来自

view?.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(press)))

view?.addGestureRecognizer(UILongPressGestureRecognizer(target: self, action: #selector(press:)))

More information here


SpriteKit 以一种非常原始的方式处理触摸事件,但它可能会让您对如何响应这些事件有更多的控制。正如 KnightOfDragon 所说,这就像重新发明轮子。

如果您想了解 SpriteKit 是如何做到的,see this example.虽然很短,但希望对您有所帮助:)

关于ios - 长按结束 swift sprite kit 时如何运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59507789/

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