iosswiftsprite-kitskspritenodesktexture

SKSpriteNode replace with SKTexture


My problem is that when I play my game, I lose my life even if the enemy does not touch my character, but flies very close to him. I understand that the problem is that the transparent space of my character is in contact with the enemy's transparent space.

I want to do as recommended in the SKPhysicsBody documentation. How can I implement this using my current code?

func madEnemy() {

    let randomNumber = Int.random(in: 1..<6)

    let enemy = SKSpriteNode(imageNamed: "enemy\(randomNumber)")

    enemy.position = CGPoint(
        x: cameraRect.maxX + enemy.size.width/2,
        y: CGFloat.random(
            min: cameraRect.minY + enemy.size.height/2,
            max: cameraRect.maxY - enemy.size.height/2))
    enemy.zPosition = 50
    enemy.name = "enemy"
    addChild(enemy)

    let actionMove =
        SKAction.moveBy(x: -(size.width + enemy.size.width), y: 0, duration: 2.0)
    let actionRemove = SKAction.removeFromParent()
    enemy.run(SKAction.sequence([actionMove, actionRemove]))
}

Solution

  • You just need to create a SKTexture object from your image first, then create a SKSpriteNode using that texture in order to use the texture for sizing the SKPhysicsBody or your node.

    func madEnemy() {
    
        let randomNumber = Int.random(in: 1..<6)
    
        let enemyTexture = SKTexture(imageNamed: "enemy\(randomNumber)")
        let enemy = SKSpriteNode(texture: enemyTexture)
        enemy.physicsBody = SKPhysicsBody(texture: enemyTexture, size: CGSize(width: enemy.size.width, height: enemy.size.height))
    
        enemy.position = CGPoint(
            x: cameraRect.maxX + enemy.size.width/2,
            y: CGFloat.random(
                min: cameraRect.minY + enemy.size.height/2,
                max: cameraRect.maxY - enemy.size.height/2))
        enemy.zPosition = 50
        enemy.name = "enemy"
        addChild(enemy)
    
        let actionMove =
            SKAction.moveBy(x: -(size.width + enemy.size.width), y: 0, duration: 2.0)
        let actionRemove = SKAction.removeFromParent()
        enemy.run(SKAction.sequence([actionMove, actionRemove]))
    }