Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Implementing anchorPoint in SKNode subclass

I have a custom class inheriting from SKNode and would like to implement SKSpriteNode's anchorPoint-like functionality on that class. Specifically, what I am trying to achieve is to center the custom node in the parent node automatically (anchorPoint at 0.5, 0.5) without having to offset it by half its width/height.

Any tips?

Edit: I ended up by first creating an anchorPoint variable and then overriding the position variable and set the super position modified by the anchorPoint.

var anchorPoint = CGPoint(x: 0.5, y: 0.5)

override var position: CGPoint {
    set {
        super.position = CGPoint(x: self.position.x - self.size.width * self.anchorPoint.x, y: self.position.y - self.size.height * self.anchorPoint.y)
    }
    get {
        return super.position
    }
}
like image 490
Rhuantavan Avatar asked Sep 29 '22 08:09

Rhuantavan


2 Answers

You can over ride the setPosition function of the inherited class. In this function you would adjust for the offset-ed anchorPoint.

For example, if you sprite is 100x100. And you have set its anchor as (.5,.5), When someone sets the position, you should add or subtract the sprite dimensions from it and then set the position. In this case, if user sets the sprite position as (0,0), you would add (100*.5,100*.5) = (50,50). And adding (0,0) to it would be (50,50).

This is the new position that you should set.

like image 92
Shamas S Avatar answered Oct 06 '22 20:10

Shamas S


It might be easier to add a new "root" SKNode under your control's SKNode, add any child nodes to it, and then just move it when the anchorPoint property is changed. That's what I did.

var anchorPoint: CGPoint = CGPoint( x: 0.5, y: 0.5 )
{
    didSet
    {
        let translateX = ( anchorPoint.x - 0.5 ) * controlSize.width
        let translateY = ( anchorPoint.y - 0.5 ) * controlSize.height
        rootNode!.position = CGPoint(x: translateX, y: translateY)
    }
}
like image 33
Brian Stewart Avatar answered Oct 06 '22 20:10

Brian Stewart