【发布时间】:2015-05-22 11:03:19
【问题描述】:
我目前有以下代码。即使代码构建成功,我似乎也无法让它工作。我正在努力做到这一点,因此当您轻弹对象时,它会以您开始和结束触摸的速度移动。
import SpriteKit
class 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)
}
//for touch: AnyObject in touches {
//let location = touch.locationInNode(self)
//let touchedNode = self.nodeAtPoint(location)
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if sprite.frame.contains(location) {
touchPoint = location
touching = true
}
}
func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
touchPoint = location
}
func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
touching = false
}
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
}
}
}}}
【问题讨论】:
-
不是 100% 确定这会有所帮助,但我认为您只想在完成轻弹后应用速度。因为您正在应用每个更新,所以您正在应用非常小的速度。您可能想尝试在 touchesMoved 中更改精灵的位置,然后根据距起点和终点的距离在 touches 结束时应用速度。您也可以根据电影的开始时间和电影的结束时间来确定它。如果你解释你得到的结果不是它的构建,也可能会有所帮助:)
-
在这里查看我的答案! stackoverflow.com/a/28259980/2158465
标签: ios swift sprite-kit physics