如何在觸摸的固定點上旋轉SpriteKit節點。所以當用戶拖動他的手指時就會變成。我也希望能夠獲得轉速。 (這個問題被問過,但我想知道如何使用SpriteKit做) 斯威夫特3個操場如何通過觸摸來旋轉SpriteNode?
我有這個迄今爲止其工作,但有時我得到一個錯誤的變種deltaAngle =角 - startingAngle!錯誤 - 「意外發現零而展開可選值」
class GameScene: SKScene {
var startingAngle:CGFloat?
var startingTime:TimeInterval?
override func didMove(to view: SKView) {
let wheel = SKSpriteNode(imageNamed: "IMG_6797.PNG")
wheel.position = CGPoint(x: 200, y: 200)
wheel.name = "wheel"
wheel.setScale(0.5)
wheel.physicsBody = SKPhysicsBody(circleOfRadius: wheel.size.width/2)
// Change this property as needed (increase it to slow faster)
wheel.physicsBody!.angularDamping = 4
wheel.physicsBody?.pinned = true
wheel.physicsBody?.affectedByGravity = false
addChild(wheel)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches {
let location = touch.location(in:self)
let node = atPoint(location)
if node.name == "wheel" {
let dx = location.x - node.position.x
let dy = location.y - node.position.y
// Store angle and current time
startingAngle = atan2(dy, dx)
startingTime = touch.timestamp
node.physicsBody?.angularVelocity = 0
}
}
}
override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches{
let location = touch.location(in:self)
let node = atPoint(location)
if node.name == "wheel" {
let dx = location.x - node.position.x
let dy = location.y - node.position.y
let angle = atan2(dy, dx)
// Calculate angular velocity; handle wrap at pi/-pi
var deltaAngle = angle - startingAngle!
if abs(deltaAngle) > CGFloat.pi {
if (deltaAngle > 0) {
deltaAngle = deltaAngle - CGFloat.pi * 2
}
else {
deltaAngle = deltaAngle + CGFloat.pi * 2
}
}
let dt = CGFloat(touch.timestamp - startingTime!)
let velocity = deltaAngle/dt
node.physicsBody?.angularVelocity = velocity
startingAngle = angle
startingTime = touch.timestamp
}
}
}
override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
startingAngle = nil
startingTime = nil
}
}
附加保護你嘗試過這麼遠嗎? ;) – Whirlwind
我最初打算使用UIKit(UiGestureRecogniser),但我在我的wwdc遊樂場中使用的SpriteKit太少,需要添加更多。我是SpriteKit的新手,所以不知道該怎麼做@Whirlwind –
你應該使用touchesBegan和touchesMoved覆蓋來獲取觸摸位置,然後計算節點應該旋轉到的切線角度。對於初學者來說,請確保您的節點圖形資源面向右側,否則您的角度將會關閉。如果您仍然需要幫助,請從那裏開始並返回一些代碼。 – TheValyreanGroup