我目前正在使用SpriteKit游戏技术开发使用
Swift编写的iOS应用程序.在这个游戏中,雨滴从屏幕顶部下降到底部.当它们到达底部时,由physicsBody表示,它们应该返回到屏幕顶部的原始位置,允许动画在游戏的整个生命周期中继续.
因为我只需要几滴我就像这样创建它们:
let drop = SKSpriteNode(imageNamed: "drop")
drop.position = CGPointMake(x,y)
drop.physicsBody = SKPhysicsBody(rectangleOfSize: drop.size)
addChild(drop)
然后我创建了位掩码:
drop.physicsBody!.categoryBitmask = DropCategory
bottom.physicsBody!.categoryBitmask = BottomCategory
drop.physicsBody!.contactTestBitmask = BottomCategory
我添加了didBeginContact函数,当drop到达底部时我会收到通知.然后我的控制台显示“击中”.
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 == BlockCategory && secondBody.categoryBitMask == GroundCategory {
println("hit ground")
firstBody.node?.removeFromParent()
let drop = SKSpriteNode(imageNamed: "drop")
drop.name = "testNode"
drop.position = CGPointMake(self.frame.width - self.frame.width/3*2, self.frame.height) // At start Position
drop.physicsBody = SKPhysicsBody(rectangleOfSize: drop.size)
drop.physicsBody?.categoryBitMask = BlockCategory
drop.physicsBody?.contactTestBitMask = GroundCategory
addChild(drop)
}
}
但是,跌落的位置不会改变.没有语法错误,所以我的问题是什么?
如果我替换它:
firstBody.node!.position = CGPointMake(x, y)
有了这个:
firstBody.applyImpulse(CGVector)
它给了一滴冲动.我怎样才能使第一个选项正常工作?
最佳答案 您可以尝试在触及底部时删除节点,并再次在顶部添加新节点.加载纹理以便在单独的SKTexture变量中重用.像这样
let dropTexture = SKTexture(imageNamed: "drop.png")
像这样使用它
let drop = SKSpriteNode(texture: dropTexture)
然后在didBeginContact里面
func didBeginContact(contact: SKPhysicsContact) {
println("collided")
var bodyA : SKPhysicsBody!
var bodyB : SKPhysicsBody!
if contact.bodyA.categoryBitMask < contact.bodyB.categoryBitMask
{
bodyA = contact.bodyA!
bodyB = contact.bodyB!
}
else
{
bodyB = contact.bodyA!
bodyA = contact.bodyB!
}
if bodyA.categoryBitMask == bottomCategoryBitMask && bodyB.categoryBitMask == raindropCategoryBitMask
{
if bodyB.node?.parent != nil // Added line
{
bodyB.node?.removeFromParent()
let drop = SKSpriteNode(imageNamed: "1.png")
drop.name = "testNode"
drop.position = CGPointMake(self.frame.width - self.frame.width/3*2, self.frame.height) // At start Position
drop.physicsBody = SKPhysicsBody(rectangleOfSize: drop.size)
drop.physicsBody?.categoryBitMask = raindropCategoryBitMask
drop.physicsBody?.contactTestBitMask = bottomCategoryBitMask
addChild(drop)
}
}
}