Dharmesh Kheni 在 Swift 3 + put label as a child of circle 和 label center alignments for the label to center in circle中的回答。
import SpriteKit
class GameScene: SKScene {
var deltaPoint = CGPoint.zero
let myLabel = SKLabelNode(fontNamed:"Chalkduster")
var circle = SKShapeNode(circleOfRadius: 100 )
override func didMove(to view: SKView) {
let color = UIColor(red: 0x00, green: 0x44, blue: 0x44, alpha: 1)
circle.position = CGPoint(x: frame.midX, y: frame.midY)
circle.strokeColor = .black
circle.glowWidth = 1.0
circle.fillColor = color
myLabel.text = "Hello, World!";
myLabel.fontSize = 20
myLabel.horizontalAlignmentMode = .center
myLabel.verticalAlignmentMode = .center
myLabel.position = CGPoint(x:circle.frame.width/2, y: circle.frame.height/2)
myLabel.fontColor = .black
// Add them into same scene
self.addChild(circle)
circle.addChild(myLabel)
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
if let touch = touches.first as? UITouch {
let currentPoint = touch.location(in: self)
let previousPoint = touch.previousLocation(in: self)
deltaPoint = CGPoint(x: currentPoint.x - previousPoint.x,y: currentPoint.y - previousPoint.y)
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
deltaPoint = CGPoint.zero
}
override func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) {
deltaPoint = CGPoint.zero
}
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
let newPoint = CGPoint(x: self.myLabel.position.x + self.deltaPoint.x,y: self.myLabel.position.y + self.deltaPoint.y)
// you can drag both item at same time
myLabel.position = newPoint
circle.position = newPoint
deltaPoint = CGPoint.zero
}
}