0
votes

I am trying to create collision for a 2d game house, such as walls, furniture, etc. But when I try to create a physics body from the texture, I only get collision on one wall.

Ive tried to set collisions with the editor and in code.

let colhouse = self.childNode(withName: "Umatilla")!
let texture = SKTexture(imageNamed: "warehouse-collisions")
colhouse.physicsBody = SKPhysicsBody(texture: texture, size: texture.size())

I want it to have collisions on the entire texture, the background is transparent, so some bodies are not touching or connected: warehouse-collisions

1
If that outside border is suppose to represent your body, then you have a problem. Bodies need to be continuous.Knight0fDragon

1 Answers

0
votes

Trying to create a single physics body from a texture with non continuous bodies is not possible with the SKPhysicsBody(texture: texture, size: texture.size()) function.

To get around this, create nodes in the editor, place them over your collision zones(only for reference). That alone will solve the issue, however if you begin to create a big map. This causes a lag problem with xcode. To get around this I then took the Width and Hight aswell as position. Then created the boundaries in code as such:

//okay so this is the first thing we have to run, setup the collisions
func setupCollisions(){
    //first we need the data
    let data = [
        SKPhysicsBody(rectangleOf: CGSize(width: 7.096, height: 180.423), center: CGPoint(x: 215.266, y: -5.504)),
        SKPhysicsBody(rectangleOf: CGSize(width: 429.879, height: 6.631), center: CGPoint(x: -3.222, y: -92.34)),
        SKPhysicsBody(rectangleOf: CGSize(width: 7.096, height: 173.735), center: CGPoint(x: -214.614, y: -2.161)),
        SKPhysicsBody(rectangleOf: CGSize(width: 43.492, height: 144.075), center: CGPoint(x: -189.318, y: -16.986)),
        SKPhysicsBody(rectangleOf: CGSize(width: 133.314, height: 45.883), center: CGPoint(x: -100.913, y: -66.08)),
        SKPhysicsBody(rectangleOf: CGSize(width: 58.041, height: 6.642), center: CGPoint(x: -182.044, y: 81.377)),
        SKPhysicsBody(rectangleOf: CGSize(width: 301.388, height: 6.662), center: CGPoint(x: 61.022, y: 81.386)),
        SKPhysicsBody(rectangleOf: CGSize(width: 89.409, height: 93.006), center: CGPoint(x: 93.072, y: -12.631))
    ]
    //now lets create a single physicsbody from all the data
    let physicsbody1 = SKPhysicsBody(bodies: data)


    physicsbody1.isDynamic = false
    self.physicsBody = physicsbody1
}

once you do it this way, remove the collisions nodes( walls, sofas, misc, etc) from the editor as we create them in code now. Just make sure to run your custom setupCollisions() function as soon as possible or needed.