3
import SpriteKit

class GameScene: SKScene 
{    
    let player = SKSpriteNode(imageNamed: "Gun")

    override func didMoveToView(view: SKView) 
    {    
        backgroundColor = SKColor.whiteColor()    
        player.position = CGPoint(x: size.width * 0.1, y: size.height * 0.5)
        addChild(player)
    }
}

func random() -> CGFloat 
{
    return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}

func random(#min: CGFloat, max: CGFloat) -> CGFloat 
{
    return random() * (max - min) + min
}

func addMonster() 
{        
    let monster = SKSpriteNode(imageNamed: "monster")        
    let actualY = random(min: monster.size.height/2, monster.size.height - monster.size.height/2)

    monster.position = CGPoint(x: monster.size.width + monster.size.width/2, y: actualY)

    // Here's the error:
    addChild(monster)

    let actualDuration = random(min: CGFloat(2.0), CGFloat(4.0))        
    let actionMove = SKAction.moveTo(CGPoint(x: -monster.size.width/2, y: actualY), duration: NSTimeInterval(actualDuration))
    let actionMoveDone = SKAction.removeFromParent()

    monster.runAction(SKAction.sequence([actionMove, actionMoveDone]))        
}

I found this on a tutorial website, and I'm planning on modifying it to some extent. However, when I try to run the code, it presents me with a "Use of unresolved identifier 'addChild'". I'm not sure how to fix this.

John Odom
  • 1,189
  • 2
  • 20
  • 35
  • Weird because SKScene is a subclass of SKNode, which provides the addChild() method. – clearlight Mar 22 '15 at 23:46
  • It is very strange. I copied it right from this tutorial: http://www.raywenderlich.com/84434/sprite-kit-swift-tutorial-beginners I did fix a few other errors, but I see no reason that this is an error. – invadingdingo Mar 22 '15 at 23:48
  • I see the same thing in a playground. I think I remember something about that in playgrounds. Have you tried it in a non-playground Xcode project? – clearlight Mar 22 '15 at 23:49
  • I see the same problem in a non-Playground project. But only in the addMonster() function. – clearlight Mar 22 '15 at 23:50
  • No, I am extremely new to this. I really just wanted to get some basic understanding, and I thought hands-on would be the best fit--reading doesn't stick as well for me. – invadingdingo Mar 22 '15 at 23:52
  • 1
    The answer which I voted up and you should too, and please also accept his answer, is correct. – clearlight Mar 22 '15 at 23:52

1 Answers1

6

Your function seems to be outside of the class, which causes the method addChild to not be found by the compiler.

You need to include all relevant methods of a class in between the class parentheses, in the same file is not good enough.

vrwim
  • 13,020
  • 13
  • 63
  • 118