gpt4 book ai didi

swift - 为什么在 SpriteKit 中检测到碰撞时转换 SKSpriteNode 有时不起作用并抛出错误

转载 作者:可可西里 更新时间:2023-11-01 01:57:18 27 4
gpt4 key购买 nike

我已经使用 swift 构建了一个游戏。首先,我创建了一个名为 alienNode 的类,它继承自 SKSpriteNode

var hP = 0

init() {
let alienTexture = SKTexture(imageNamed: "Alien_Normal.png")
self.hP = 5
super.init(texture: alienTexture, color: UIColor.white, size: alienTexture.size())
}

required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}

然后我在 GameScene 中创建了 3 个外星人

func buildAlien() {
for i in 0...2 {
let alienNode = AlienNode()
addChild(alienNode)
alienNode.name = kAlienName
let position_i_Factor = i - 1
alienNode.position = CGPoint(x: size.width / 2 + CGFloat(position_i_Factor * 130), y: size.height / 2 + 200)

alienNode.physicsBody = SKPhysicsBody(texture: alienNode.texture!, size: alienNode.size)
alienNode.physicsBody?.affectedByGravity = false
alienNode.physicsBody?.allowsRotation = false

alienNode.physicsBody?.mass = 1000000


alienNode.physicsBody?.categoryBitMask = BodyType.alien.rawValue
alienNode.physicsBody?.contactTestBitMask = BodyType.bullet.rawValue
}

当我发射子弹时,它能很好地检测到碰撞,但当我转换时
SKSpriteNode转AlienNode,效果不好,有时会抛出
错误。

这是 didBegin() 中的代码

    let nodesName = [contact.bodyA.node?.name,contact.bodyB.node?.name]
print(nodesName)

if nodesName.contains(kAlienName) && nodesName.contains(kBulletName) {
//A bullet hit a alien
contact.bodyB.node?.removeFromParent() //remove the bullet
print("hit")
let alienNode = contact.bodyA.node as! AlienNode// it doesn't work sometimes
alienNode.hP -= 1
if alienNode.hP <= 0 {
alienNode.removeFromParent()
print("Alien killed")
}

我的代码有什么问题吗,我该如何解决。真的非常感谢!

最佳答案

我猜@OOPer 在他的评论中暗示的是:

您如何知道AlienNodebodyA.node

bodyB.node 就不能很好吗?

你开始用这个来填充你的 nodesName 数组

let nodesName = [contact.bodyA.node?.name,contact.bodyB.node?.name]

接下来检查 nodesName 实际上包含 kAlienNamekBulletName

if nodesName.contains(kAlienName) && nodesName.contains(kBulletName) {

但是您仍然不知道nodesName 数组中节点的顺序

有时 bodyA.node 可能是一个 AlienNode,有时它可能是 bodyB.node

我想像这样的东西可以工作:

if nodesName.contains(kAlienName) && nodesName.contains(kBulletName) {
//find the alien node
var alienNode: AlienNode?
if let _ = contact.bodyA.node as? AlienNode {
//it was a
alienNode = contact.bodyA.node as? AlienNode
contact.bodyB.node?.removeFromParent() //remove the bullet
} else {
//it was b
alienNode = contact.bodyB.node as? AlienNode
contact.bodyA.node?.removeFromParent() //remove the bullet
}
print("hit")
//it should be safe to force unwrap here
alienNode!.hP -= 1
if alienNode!.hP <= 0 {
alienNode!.removeFromParent()
print("Alien killed")
}

它未经测试,但希望你能理解。

希望对您有所帮助。

关于swift - 为什么在 SpriteKit 中检测到碰撞时转换 SKSpriteNode 有时不起作用并抛出错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51219706/

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