Could somebody please help me with this issue: I can't understand why my SKScene moves few points right when I try to add aspect ratio to background image (I removed transparency from scene so you can see the problem with it's size)? Is this swiftUI bug or I am doing something wrong?
import SwiftUI
import SpriteKit
struct MenuScreenView: View {
@Bindable var player: Player
private let screenWidth = UIScreen.main.bounds.width
private let screenHeight = UIScreen.main.bounds.height
var scene: SKScene {
let scene = MenuScene()
scene.scaleMode = .resizeFill
scene.size = CGSize(width: screenWidth, height: screenHeight)
return scene
}
// MARK: - Body
var body: some View {
ZStack {
Image("background2")
.resizable()
.aspectRatio(contentMode: .fill)
.ignoresSafeArea()
SpriteView(scene: scene)
.frame(width: screenWidth, height: screenHeight, alignment: .center)
.edgesIgnoringSafeArea(.all)
}
}
}
// MARK: - Preview
#Preview {
MenuScreenView(player: Player(name: "Name", score: 100, ship: .frigate, ammo: [.missile: 100]))
}
import SpriteKit
class MenuScene: SKScene {
override init() {
super.init(size: UIScreen.main.bounds.size)
self.backgroundColor = .clear
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didMove(to view: SKView) {
super.didMove(to: view)
setupUI()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let touch = touches.first else { return }
let location = touch.location(in: self)
let nodesAtPoint = nodes(at: location)
for node in nodesAtPoint {
if let nodeName = node.name {
print("\(nodeName) button tapped!")
}
}
}
private func setupUI() {
if isSavedGameExist() {
createMenuButtonWith(continueTitle, at: CGPoint(x: frame.midX, y: frame.midY + 60))
}
createMenuButtonWith(newGameTitle, at: CGPoint(x: frame.midX, y: frame.midY + 20))
createMenuButtonWith(scoreTitle, at: CGPoint(x: frame.midX, y: frame.midY - 20))
createMenuButtonWith(settingsTitle, at: CGPoint(x: frame.midX, y: frame.midY - 60))
}
private func createMenuButtonWith(_ text: String, at position: CGPoint) {
let button = MenuButton(buttonText: text)
button.position = position
addChild(button)
}
private func isSavedGameExist() -> Bool {
// TODO: Add logic of check for existing game
return true
}
// MARK: - Localization helpers
private var newGameTitle: String {
NSLocalizedString(Localizable.menuNewGameButtonTitle, comment: "")
}
private var settingsTitle: String {
NSLocalizedString(Localizable.menuSettingsButtonTitle, comment: "")
}
private var scoreTitle: String {
NSLocalizedString(Localizable.menuScoreButtonTitle, comment: "")
}
private var continueTitle: String {
NSLocalizedString(Localizable.menuContinueButtonTitle, comment: "")
}
}
[bug is here] (https://i.stack.imgur.com/M1HNX.png)