gpt4 book ai didi

ios - 使用 SpriteKit 设置地面节点?

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

我一直在设计一款游戏,希望球一接触地面就停止游戏。我下面的功能是为了设置地面。

class GameScene: SKScene, SKPhysicsContactDelegate {

var ground = SKNode()

let groundCategory: UInt32 = 0x1 << 0
let ballCategory: UInt32 = 0x1 << 1

//Generic Anchor coordinate points
let anchorX: CGFloat = 0.5
let anchorY: CGFloat = 0.5
/*Sets the background and ball to be in the correct dimensions*/

override init(size: CGSize) {
super.init(size: size)

//Create the Phyiscs of the game
setUpPhysics()

setUpGround()

setUpBall()
}

func setUpPhysics() -> Void {
self.physicsWorld.gravity = CGVectorMake( 0.0, -5.0 )
self.physicsWorld.contactDelegate = self
}

func setUpGround() -> Void {
self.ground.position = CGPointMake(0, self.frame.size.height)
self.ground.physicsBody = SKPhysicsBody(rectangleOfSize: CGSizeMake(self.frame.size.width, self.frame.size.height)) //Experiment with this
self.ground.physicsBody?.dynamic = false

self.ground.physicsBody?.categoryBitMask = groundCategory //Assigns the bit mask category for ground
self.ball.physicsBody?.contactTestBitMask = ballCategory //Assigns the contacts that we care about for the ground

/*Added in*/
self.ground.physicsBody?.dynamic = true

self.ground.physicsBody?.affectedByGravity = false
self.ground.physicsBody?.allowsRotation = false
/**/

self.addChild(self.ground)
}

func setUpBall() -> Void {

ball.anchorPoint = CGPointMake(anchorX, anchorY)

self.ball.position = CGPointMake(self.frame.size.width/2, self.frame.size.height/2)

self.ball.name = "ball"
self.ball.userInteractionEnabled = false

ball.physicsBody?.usesPreciseCollisionDetection = true

self.ball.physicsBody?.categoryBitMask = ballCategory //Assigns the bit mask category for ball
self.ball.physicsBody?.collisionBitMask = wallCategory | ceilingCategory //Assigns the collisions that the ball can have
self.ball.physicsBody?.contactTestBitMask = groundCategory //Assigns the contacts that we care about for the ball

addChild(self.ball) //Add ball to the display list
}

我注意到的问题是,当我运行 iOS 模拟器时,未检测到接地节点。在这种情况下我做错了什么?

最佳答案

你的地面节点根本没有出现吗?我相信你的地面应该是一个 SKSpriteNode。将该 SKSpriteNode 添加为您创建的 SKNode 对象的子对象。SKNode 是一个空节点,而 SKSpriteNode 具有实际的视觉表示。与其在单独的函数中执行,不如在 DidMoveToView 本身中执行会简单得多。

var objects = SKNode()
addChild(objects)
let ground = SKNode()
ground.position = .......
let colorsprite1 = SKSpriteNode(imageNamed: "yourimageoftheground")
ground.addChild(colorsprite1)
ground.physicsBody?.dynamic = false

是的,您将地面的物理定义设置为非动态是正确的。我不知道为什么人们不这么告诉你。你不希望它在接触到你的球或你在场景中移动的任何东西时移动。

添加您需要的所有其他物理定义。考虑使用 ContactTestBitMask,因为您希望 SpriteKit 通知您何时发生与地面的碰撞,而不是 SpriteKit 自己处理。在 StackOverFlow 中可以通过示例轻松获得有关该掩码的详细信息。

objects.addChild(ground)

希望对你有帮助

关于ios - 使用 SpriteKit 设置地面节点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32526283/

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