所以我有一个非常基本的弹弓,它有两个物理体,用SKPhysicsSpringJoint连接在一起。当触摸开始时,我创建了一个弹丸和弹簧。当触摸被移动时,我根据用户的触摸位置移动投射物。当触碰结束时,射弹就发射了。
问题是,每当用户停止移动投射物,但没有松开,投射物就会朝着它的锚点移动,并围绕它摆动,直到用户释放他们的触摸。我已经工作了几个小时,试图弄清楚为什么会发生这种事情,有什么想法吗?
以下是主要函数:
override func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let touchLocation = touch.locationInNode(self)
//Add Cannon Ball
var uniqueID:Int = nodeArray.count
var uniqueString = "cannonBall\(uniqueID)"
var cannonBall = CannonBallNode(location: CGPoint(x: size.width/2, y: 200))
cannonBall.name = uniqueString
// 3 - Determine offset of location to projectile
let offset = touchLocation - cannonBall.position
// 4 - Bail out if you click above cannon
if (offset.y > 50) { return }
self.addChild(cannonBall)
println("\(nodeArray.count)")
if var cannon = childNodeWithName("cannon") {
if var heldCannonBall = childNodeWithName(uniqueString) {
heldCannonBall.physicsBody?.affectedByGravity = false
var spring = SKPhysicsJointSpring.jointWithBodyA(cannon.physicsBody, bodyB: cannonBall.physicsBody, anchorA: cannon.position, anchorB: cannonBall.position)
spring.damping = 0.4;
spring.frequency = 1.0;
// Add Physics
physicsWorld.addJoint(spring)
}
}
}
}
override func touchesMoved(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let touchLocation = touch.locationInNode(self)
var uniqueID:Int = nodeArray.count
var uniqueString = "cannonBall\(uniqueID)"
if var heldCannonBall = childNodeWithName(uniqueString) {
// 3 - Determine offset of location to projectile
let offset = touchLocation - heldCannonBall.position
// 4 - Bail out if you are shooting down or backwards
if (offset.y > 0) { return }
heldCannonBall.position = touchLocation
}
}
}
override func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) {
for touch: AnyObject in touches {
let touchLocation = touch.locationInNode(self)
var uniqueID:Int = nodeArray.count
var uniqueString = "cannonBall\(uniqueID)"
if var releasedCannonBall = childNodeWithName(uniqueString) {
var angle = CGFloat(M_PI_4)
var magnitude:CGFloat = 1;
releasedCannonBall.physicsBody?.applyImpulse(CGVectorMake(magnitude*cos(angle), magnitude*sin(angle)))
releasedCannonBall.physicsBody?.affectedByGravity = true
}
runAction(SKAction.sequence([
SKAction.runBlock{[self.physicsWorld.removeAllJoints()]},
SKAction.waitForDuration(0.1)]
))
nodeArray.append("\(uniqueString)")
}
}发布于 2015-04-28 05:08:55
终于找到了解决方案!我需要生成一个更新函数来更新弹丸的位置,因为它是通过touchesMoved函数移动的。我创建了一个全局变量,并让它存储触摸开始和移动时的位置。我把它放在更新函数中,瞧,没有更多的问题。
override func update(currentTime: CFTimeInterval) {
/* Called before each frame is rendered */
//#1
var uniqueID:Int = nodeArray.count
var uniqueString = "cannonBall\(uniqueID)"
println("\(cannonBallLocation)")
if var releasedCannonBall = childNodeWithName(uniqueString) {
releasedCannonBall.position = cannonBallLocation
}
} //end funchttps://stackoverflow.com/questions/29905014
复制相似问题