Lockchain
Lockchain

Reputation: 37

Setting SKSpriteNodes position from custom SKSpriteNode class

I want to set the position of a skspritenode(hero) in my gamescene when I assign my class(Character) to it.

When its given the CGPoints frame.midX and frame.midY it doesn't know what frame its in reference to, so it shows up somewhere completely different.

Any idea how I can fix my class so that the cPosition will actually set the position of my hero in my gamescene ?

Class code

class Character: SKSpriteNode{

    var cSize: CGSize
    var cColor: UIColor
    let cName: String
    let cTexture: SKTexture
    let cPosition: CGPoint

    init(cTexture: SKTexture,cSize: CGSize,cColor: UIColor, cName: String,cPosition: CGPoint){

        self.cSize = cSize
        self.cColor = cColor
        self.cName = cName
        self.cTexture = cTexture
        self.cPosition = cPosition

        super.init(texture: cTexture, color: cColor, size: cSize)
    }

    func jump(xForce: CGFloat, yForce: CGFloat){
        physicsBody?.applyImpulse(CGVector(dx: xForce, dy: yForce))            
    }

Method where my Character class is assigned to my hero:

     func addHero() {

            let hero = Character(cTexture: SKTexture(imageNamed: "testAvacado.png") ,cSize: CGSize(width: 68, height: 28), cColor: .blue, cName: "hero",
cPosition: CGPoint(x: frame.midX, y: frame.midY))

            hero.physicsBody = SKPhysicsBody(texture: hero.cTexture, size: hero.cSize)

            addChild(hero)
        }

Upvotes: 1

Views: 38

Answers (1)

Arie Pinto
Arie Pinto

Reputation: 1292

You're not actually positioning your sprite, the cPosition variable does nothing at the moment. Change your init method like this:

var cSize: CGSize
var cColor: UIColor
let cName: String
let cTexture: SKTexture
//let cPosition: CGPoint

init(cTexture: SKTexture,cSize: CGSize,cColor: UIColor, cName: String,cPosition: CGPoint) {

    self.cSize = cSize
    self.cColor = cColor
    self.cName = cName
    self.cTexture = cTexture
    //self.cPosition = cPosition

    super.init(texture: cTexture, color: cColor, size: cSize)

    self.position = cPosition
}

Upvotes: 1

Related Questions