Nio Pullus
Nio Pullus

Reputation: 55

Swift - Label and Sprite position contrast

I am fairly new to Swift but along the way I noticed something strange. If I have a sprite and a label and enter the exact same position for each of them, they'll both have a different visual position. I am looking for someone to explain this as to better my understanding of Swift. Here's the output:

screenshot

//
//  GameScene.swift
//  Test Game
//
//  Created by NioPullus on 9/7/15.
//  Copyright (c) 2015 Owen Vnek. All rights reserved.
//

import SpriteKit

class GameScene: SKScene {

    var testSprite: SKSpriteNode = SKSpriteNode(imageNamed:                           "Spaceship")
    var testLabel: UILabel = UILabel()

    func defineTestSprite(var #sprite: SKSpriteNode) -> SKSpriteNode {
        sprite.position.x = 100
        sprite.position.y = 100
        sprite.xScale = 0.3
        sprite.yScale = 0.3
        return sprite
    }

    func defineTestLabel(var #label: UILabel) -> UILabel {
        label = UILabel(frame: CGRect(x: 100, y: 100, width: 100, height: 100))
        label.text = "Test"
        return label
    }

    override func didMoveToView(view: SKView) {
        self.addChild(defineTestSprite(sprite: self.testSprite))
        self.view?.addSubview(defineTestLabel(label:self.testLabel))
    }

    override func touchesBegan(touches: Set<NSObject>, withEvent event:     UIEvent) {
        /* Called when a touch begins */

        for touch in (touches as! Set<UITouch>) {
            let location = touch.locationInNode(self)
        }
    }

    override func update(currentTime: CFTimeInterval) {
        /* Called before each frame is rendered */
    }
}

Upvotes: 1

Views: 225

Answers (1)

jtbandes
jtbandes

Reputation: 118681

UIKit and SpriteKit use different coordinate systems, so you wouldn't necessarily expect a sprite with the same x/y values as a subview to appear in the same visual position.

You can use the SKView method convertPoint:toScene: (and convertPoint:fromScene:) to convert between these coordinate spaces.

You can find out more information about the SpriteKit coordinate system here, and the UIView coordinate system here. (As you can see, they are very different.)

Upvotes: 1

Related Questions