我想使用Swift和SpriteKit为iOS重现Super-Mario。我使用SKPhysics-bodies来模拟玩家和环境之间的碰撞。玩家和所有对象都有自己的SKPhysicsBody(其大小的矩形)。但是当玩家跳过一块砖(从左上角或右上角)like this时,玩家就会陷入困境。
我的假设是,当两个SKSpriteNodes发生碰撞时,它们会重叠一点点。并且SKPhysics-Engine认为玩家位于中间砖的顶部,因为玩家在砖块上方有一点点,并且落在中间砖上。
所以我的问题是:如何防止SKSPriteNodes重叠?或者我该如何解决这个问题?
P.S。如果您需要更多信息,请告诉我!
编辑:砖类的一些代码:
import SpriteKit
class Brick: SKSpriteNode {
let imgBrick = SKTexture(imageNamed: "Brick")
init(let xCoor: Float, let yCoor: Float) {
// position is a global variable wich is 1334/3840
super.init(texture: imgBrick, color: UIColor.clearColor(), size: CGSize(width: 80*proportion, height: 80*proportion))
position = CGPoint(x:Int(xCoor*667)+Int(40*proportion), y:Int(375-(yCoor*375))-Int(40*proportion))
name = "Brick"
physicsBody = SKPhysicsBody(rectangleOfSize: self.size)
physicsBody?.affectedByGravity = false
physicsBody?.dynamic = false
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
和我的玩家类
import SpriteKit
class Mario: SKSpriteNode {
let atlas = SKTextureAtlas(named: "Mario")
var imgMario = [SKTexture]()
var action = SKAction()
init(let xCoor: Float, let yCoor: Float) {
for(var i = 1; i < 24; i++) {
imgMario.append(atlas.textureNamed("X\(i)"))
}
super.init(texture: imgMario[0], color: UIColor.clearColor(), size: CGSize(width: 120*proportion, height: 160*proportion))
position = CGPoint(x:Int(xCoor)+Int(60*proportion), y:Int(yCoor)-Int(90*proportion))
name = "Mario"
physicsBody = SKPhysicsBody(rectangleOfSize: self.size)
physicsBody?.allowsRotation = false
action = SKAction.repeatActionForever(SKAction.animateWithTextures(imgMario, timePerFrame: 0.03, resize: false, restore: true))
runAction(action, withKey: "walking")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
和我的等级等级的一部分
class Level: SKScene, SKPhysicsContactDelegate {
var motionManager = CMMotionManager()
var mario = Mario(xCoor: 100, yCoor: 90)
var world = SKSpriteNode()
let MarioCategory: UInt32 = 0x1 << 0
let BrickCategory: UInt32 = 0x1 << 1
/*
Some more code...
*/
func setUpPhysics() {
physicsWorld.contactDelegate = self
mario.physicsBody!.categoryBitMask = marioCategory
mario.physicsBody?.collisionBitMask = brickCategory
mario.physicsBody?.contactTestBitMask = brickCategory
for(var i = 0; i < world.children.count; i++) {
if(world.children[i].name == "Brick") {
world.children[i].physicsBody?.categoryBitMask = brickCategory
world.children[i].physicsBody?.collisionBitMask = marioCategory
world.children[i].physicsBody?.contactTestBitMask = marioCategory
world.children[i].physicsBody?.friction = 0
}
}
}
}
答案 0 :(得分:0)
尝试将物理上的UsePreciseCollisionDetection设置为true。
mario.physicsBody?.usesPreciseCollisionDetection = true
https://developer.apple.com/reference/spritekit/skphysicsbody有一些例子。
通过将此属性设置为true,可以使其更准确地检测碰撞,因此只有在您的意思是这样时。我还重新考虑给每个块自己的物理体。您只关心一组块的边缘而不是每个块的边缘。
另一个建议是你可以根据纹理创建一个物理体。因此,如果您的SKSpriteNode具有带透明位的复杂纹理,您可以创建另一个仅仅是简单黑色块或类似纹理的纹理,这将有助于引擎检测更准确的碰撞。