gpt4 book ai didi

xcode - 检测碰撞 SpriteKit Swift

转载 作者:可可西里 更新时间:2023-11-01 01:37:32 25 4
gpt4 key购买 nike

碰撞检测不是在 didBeginContact 函数中调用 NSLog。物理学工作正常......有人可以告诉我我做错了什么吗?我尝试过的一切都给了我相同的结果。

import SpriteKit

class GameScene: SKScene, SKPhysicsContactDelegate {

let category0: UInt32 = 0x1 << 0
let category1: UInt32 = 0x1 << 1
let category2: UInt32 = 0x1 << 2
let category3: UInt32 = 0x1 << 4
let position1:CGFloat = 100

override func didMoveToView(view: SKView) {

self.physicsBody = SKPhysicsBody (edgeLoopFromRect:self.frame)
self.physicsWorld.gravity = CGVectorMake(0, -9)
physicsWorld.contactDelegate = self

let ground = SKSpriteNode(color: UIColor .redColor(), size: CGSizeMake(self.size.width, self.size.height/16))
ground.position = CGPointMake(self.size.width/2, self.size.height - self.size.height + ground.size.height)
ground.zPosition = position1
self.addChild(ground)
ground.physicsBody = SKPhysicsBody(rectangleOfSize: ground.size)
ground.physicsBody?.categoryBitMask = category2
ground.physicsBody?.contactTestBitMask = category1
ground.physicsBody?.collisionBitMask = category1
ground.physicsBody?.dynamic = false
ground.physicsBody?.affectedByGravity = false
ground.name = "Ground"

let launchingPad = SKSpriteNode(color: UIColor .redColor(), size: CGSizeMake(self.size.width/6, self.size.height/16))
launchingPad.position = CGPointMake(self.size.width - launchingPad.size.width/2 - 5, self.size.height - self.size.height + launchingPad.size.height * 4)
launchingPad.zPosition = position1
self.addChild(launchingPad)
launchingPad.physicsBody = SKPhysicsBody(rectangleOfSize: launchingPad.size)
launchingPad.physicsBody?.categoryBitMask = category1
launchingPad.physicsBody?.contactTestBitMask = category2
launchingPad.physicsBody?.collisionBitMask = category2
launchingPad.physicsBody?.dynamic = true
launchingPad.physicsBody?.affectedByGravity = true
launchingPad.name = "LaunchingPad"

func didBeginContact(contact: SKPhysicsContact) {

let firstBody = contact.bodyA.node as! SKSpriteNode

let secondBody = contact.bodyB.node as! SKSpriteNode

if ((firstBody.name == "LaunchingPad") && (secondBody.name == "Ground")){

NSLog("Contact")

}}}}

最佳答案

根据 KnightOfDragon 的评论回答我自己的问题。这是工作方法。

func didBeginContact(contact: SKPhysicsContact) {

var firstBody: SKPhysicsBody
var 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 == category1) && (secondBody.categoryBitMask == category2)){
NSLog("contact")
}
}

关于xcode - 检测碰撞 SpriteKit Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34903904/

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