gpt4 book ai didi

swift - SpriteKit 构建绳索功能不起作用

转载 作者:搜寻专家 更新时间:2023-11-01 06:34:14 26 4
gpt4 key购买 nike

这是我的代码:

 var red: SKSpriteNode?
var redHolding = false
/////
// MARK: didMove
/////
override func didMove(to view: SKView) {
physicsWorld.contactDelegate = self

if let r = self.childNode(withName: "red") as? SKSpriteNode { red = r }
createRope(red!, 10)

}//

func createRope(_ anchorSprite: SKSpriteNode, _ numOfLinks: Int) {
var links: [SKSpriteNode] = []
anchorSprite.position = CGPoint(x: 0, y: 0)

for i in 0...numOfLinks {
let link = SKSpriteNode(color: UIColor.black, size: CGSize(width: 20, height: 30))
link.position = CGPoint(x: anchorSprite.frame.midX, y: anchorSprite.frame.minY - link.frame.height/2)
link.physicsBody? = SKPhysicsBody(rectangleOf: link.size)
link.physicsBody?.isDynamic = true
link.physicsBody?.allowsRotation = true
link.physicsBody?.affectedByGravity = true
link.physicsBody?.categoryBitMask = 4
self.addChild(link)
var joint = SKPhysicsJointPin()
links.append(link)
if i == 0 {
joint = SKPhysicsJointPin.joint(withBodyA: anchorSprite.physicsBody!, bodyB: link.physicsBody!, anchor: CGPoint(x: anchorSprite.frame.midX, y: anchorSprite.frame.minY))
} else {
link.position = CGPoint(x: anchorSprite.frame.midX, y: (links[i-1].frame.minY - links[i-1].frame.height/2) - link.frame.height/2)
joint = SKPhysicsJointPin.joint(withBodyA: links[i-1].physicsBody!, bodyB: links[i].physicsBody!, anchor: CGPoint(x: links[i-1].frame.minX, y: links[i-1].frame.minY))
}
physicsWorld.add(joint)
}
}

我正在尝试构建一个以编程方式创建绳索的函数,到目前为止我可能还差得远,但我遇到了一个问题,我不明白为什么。

我收到错误“在展开可选时意外发现 nil”

当我尝试制作关节时,“链接”变量及其物理体会发生这种情况。

我不明白为什么,我一直在四处移动以尝试修复它,但没有成功。

有人看到代码有什么问题吗?

感谢您的帮助。

最佳答案

您需要删除 linkphysicsBody 属性之后的 ?

旧的:

link.physicsBody? = SKPhysicsBody(rectangleOf: link.size)

新:

link.physicsBody = SKPhysicsBody(rectangleOf: link.size)

关于swift - SpriteKit 构建绳索功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43427716/

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