这是我写的一个简单示例,它通过模拟游戏循环中的速度而不是直接设置位置来触摸来移动精灵。这使子画面更具动态性(即,您可以“扔”它,并在拖动子画面时使其与其他物理物体进行交互)。无需进行角度计算,我只是计算在一定时间间隔内将精灵移动到触摸位置所需的速度。在这种情况下,我将时间设置为1/60,以便立即应用运动,从而使对象显得反应灵敏。
import SpriteKitclass GameScene: SKScene { var sprite: SKSpriteNode! var touchPoint: CGPoint = CGPoint() var touching: Bool = false override func didMoveToView(view: SKView) { self.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame) sprite = SKSpriteNode(color: UIColor.redColor(), size: CGSize(width: 50, height: 50)) sprite.physicsBody = SKPhysicsBody(rectangleOfSize: sprite.size) sprite.position = CGPoint(x: self.size.width/2.0, y: self.size.height/2.0) self.addChild(sprite) } override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { let touch = touches.first as! UITouch let location = touch.locationInNode(self) if sprite.frame.contains(location) { touchPoint = location touching = true } } override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) { let touch = touches.first as! UITouch let location = touch.locationInNode(self) touchPoint = location } override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { touching = false } override func update(currentTime: CFTimeInterval) { if touching { let dt:CGFloat = 1.0/60.0 let distance = CGVector(dx: touchPoint.x-sprite.position.x, dy: touchPoint.y-sprite.position.y) let velocity = CGVector(dx: distance.dx/dt, dy: distance.dy/dt) sprite.physicsBody!.velocity=velocity } }}您可以自己调整物理量计算,以获得所需的效果。但是这段代码应该足以让您入门。我想到的一些增强功能可能会限制速度,以使对象在释放时不会移动得太快。给触摸拖动增加延迟,以便移动精灵,但意外地在结尾处短暂停止,则继续抛出对象。



