gpt4 book ai didi

ios - 无法在 SpriteKit 中的坐标空间之间进行转换

转载 作者:行者123 更新时间:2023-11-28 06:02:12 27 4
gpt4 key购买 nike

我正在尝试让 SKShapeNode 跟随 UITouch

我的问题是 UITouch 的位置是相对于屏幕左下角的,而 SKShapeNode 的位置是相对于我给出的位置当我创建它时,它位于屏幕的中心。

例如:ball 以 (189.0, 335.0) 为中心,即 View 的中心。我点击球,触摸的位置告诉我触摸事件发生在 (189.0, 335.0),但是 ball.position 会告诉我 (0.0, 0.0)。如何获取在 View 坐标系中的位置?

import SpriteKit
import GameplayKit

class GameScene: SKScene {

var touched = false
var location = CGPoint.zero
var ball: SKShapeNode = SKShapeNode(circleOfRadius: 15)
var background: SKSpriteNode = SKSpriteNode(imageNamed: "background")

override func didMove(to view: SKView) {
background.size = frame.size
background.position = CGPoint(x: view.frame.size.width / 2, y: view.frame.size.height / 2)
addChild(background)

let path = CGMutablePath()
path.addArc(center: CGPoint(x: view.frame.size.width / 2, y: view.frame.size.height / 2),
radius: 15,
startAngle: 0,
endAngle: CGFloat.pi * 2,
clockwise: false)
ball = SKShapeNode(path: path) // Added to center of screen
ball.lineWidth = 1
ball.fillColor = .cyan
ball.strokeColor = .cyan
ball.glowWidth = 0.5
addChild(ball)
print(ball.position)
}


override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
moveNode()
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
touched = true
for touch in touches {
location = touch.location(in: view)
}
}

override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
location = touch.location(in: view)

}
}

override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
touched = false
}

func moveNode() {
if touched {
let speed: CGFloat = 1
if location.x < ball.position.x {
let newLocation = ball.position.x - speed
ball.position = CGPoint(x: newLocation, y: ball.position.y)
} else {
let newLocation = ball.position.x + speed
ball.position = CGPoint(x: newLocation, y: ball.position.y)
}
}
}
}

最佳答案

您永远不会将球的位置设置为 (0,0)。问题是球位于 (0,0),但它的路径代表球坐标中的 (189,335) 处的某物。更改为:

override func didMove(to view: SKView) {
background.size = frame.size
background.position = CGPoint(x: view.frame.size.width / 2, y: view.frame.size.height / 2)
addChild(background)

let path = CGMutablePath()
// construct a path relative to center of the ball
path.addArc(center: CGPoint(x: 0, y: 0),
radius: 15,
startAngle: 0,
endAngle: CGFloat.pi * 2,
clockwise: false)
ball = SKShapeNode(path: path)
// locate the ball at the center of the screen
ball.position = CGPoint(x: view.frame.size.width / 2, y: view.frame.size.height / 2)
ball.lineWidth = 1
ball.fillColor = .cyan
ball.strokeColor = .cyan
ball.glowWidth = 0.5
addChild(ball)
print(ball.position)
}

关于ios - 无法在 SpriteKit 中的坐标空间之间进行转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49291248/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com