Search code examples
swiftuiviewsprite-kitpositionconstraints

SpriteKit/UIKit - How to set the position of UIView to the position of a Node?


I have created a UIImageView that should have the same position of the associated node but since the coordinates of the UIView do not equal the coordinates of the Node the view is sometimes in the wrong position.

So the question is if there is a method to position the Image in the node and stay there.

Here you can see the result of the code below

Thank you in advance.

import SpriteKit

class GameScene: SKScene {

var player = SKSpriteNode()
var frames : Array = [UIImage]()
var playerView = UIImageView()


override func didMove(to view: SKView) {

    player = SKSpriteNode(color: .clear , size: CGSize(width: 50,     height: 100))

    player.physicsBody = SKPhysicsBody(rectangleOf: player.size)
    player.physicsBody?.affectedByGravity = false

    for i in 1...6 {
        frames.append(UIImage(named: "playerRunLeft-\(i)")!)
        playerView.contentMode = .topLeft
    }

    player.position = CGPoint(x: 0, y: 0)

    playerView.animationImages = frames
    playerView.animationDuration = 0.5
    playerView.contentScaleFactor = 6
    playerView.frame.origin = CGPoint(x: view.center.x , y: view.center.y)
    playerView.startAnimating()

    addChild(player)
    view.addSubview(playerView)
}
}

Solution

  • So I finally found a solution:

    let adjustRatioY = -(view.frame.height / scene!.frame.height)*player.position.y - 24
    let adjustRatioX = (view.frame.width / scene!.frame.width)*player.position.x - 15
    
    playerView.center = CGPoint(x: view.center.x + adjustRatioX , y: view.center.y + adjustRatioY )
    

    I have used this function and it works perfectly. In case somebody has the same problem: You have to adjust -24 and 15 manually to center the UIImageView so:

    playerView.center = view.center //(adjust here)
    

    Player.position should be (0/0) for the adjustment.