gpt4 book ai didi

ios - SpriteKit/Swift - 当两个节点已经接触时如何检查它们的接触

转载 作者:行者123 更新时间:2023-11-28 06:44:33 26 4
gpt4 key购买 nike

在我的游戏中,当游戏开始时,一些节点已经接触,但我找不到如何检测这些接触。我只成功检测到节点在游戏过程中移动并使用函数 didBeginContact 进行接触时发生的接触。

有人知道如何检测这些联系人吗?

如果需要,这是我的 didBeginContact:

func didBeginContact(contact: SKPhysicsContact) {

var firstBody: SKPhysicsBody
var secondBody: SKPhysicsBody
if contact.bodyA.categoryBitMask == contact.bodyB.categoryBitMask {
firstBody = contact.bodyA
secondBody = contact.bodyB

contactsList.append([firstBody.node!,secondBody.node!])
}
}

最佳答案

我刚刚尝试让两个 Sprite 从一开始就重叠,并为我检测到接触。这是代码:

import SpriteKit

struct Collider {
static let SmallSquare : UInt32 = 1 << 0
static let BigSquare : UInt32 = 1 << 1
}

class GameScene: SKScene, SKPhysicsContactDelegate {

override func didMoveToView(view: SKView) {

self.physicsWorld.contactDelegate = self

let smallSquare = SKSpriteNode(color: .orangeColor(), size: CGSize(width: 50, height:50))
smallSquare.zPosition = 2
smallSquare.position = CGPoint(x: frame.midX, y: frame.midY)
smallSquare.physicsBody = SKPhysicsBody(rectangleOfSize: smallSquare.size)
smallSquare.physicsBody?.affectedByGravity = false
smallSquare.physicsBody?.categoryBitMask = Collider.SmallSquare
smallSquare.physicsBody?.contactTestBitMask = Collider.BigSquare
smallSquare.physicsBody?.collisionBitMask = 0
addChild(smallSquare)

let bigSquare = SKSpriteNode(color: .purpleColor(), size: CGSize(width: 200, height: 200))
bigSquare.zPosition = 1
bigSquare.position = CGPoint(x: frame.midX, y: frame.midY)
bigSquare.physicsBody = SKPhysicsBody(rectangleOfSize: bigSquare.size)
bigSquare.physicsBody?.affectedByGravity = false
bigSquare.physicsBody?.categoryBitMask = Collider.BigSquare
bigSquare.physicsBody?.contactTestBitMask = Collider.SmallSquare
bigSquare.physicsBody?.collisionBitMask = 0
addChild(bigSquare)

}

func didBeginContact(contact: SKPhysicsContact) {

print("Contact detected")
}
}

稍后,为了适本地检测某些物体之间的接触,您应该这样做:

func didBeginContact(contact: SKPhysicsContact) {

var firstBody, secondBody: SKPhysicsBody

if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask {

firstBody = contact.bodyA
secondBody = contact.bodyB
} else {

firstBody = contact.bodyB
secondBody = contact.bodyA
}


if ((firstBody.categoryBitMask & Collider.SmallSquare) != 0 &&
(secondBody.categoryBitMask & Collider.BigSquare != 0)) {

print ("Contact detected")
}

}

但即使没有它,该消息也会在第一次启动游戏时打印出来,因为物理世界无论如何都会检测到接触。

关于ios - SpriteKit/Swift - 当两个节点已经接触时如何检查它们的接触,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36874305/

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