如何将applyForce()用于SCNNode以使其朝向另一个SCNNode的方向?
我知道两个节点的位置。
我知道我可以使用SCNAction.move(to:position,duration:3),但这不符合我的需要 - 因为我不希望每个节点都花费相同的持续时间到达目的地。我希望所有节点以相同的速度行进。
目标是让子弹离开一个节点并转向另一个节点。无需更新路径(如真正的子弹)。
let bullet = SCNNode(geometry: SCNSphere(radius : 0.1))
bullet.position = enemy.position
bullet.physicsBody = SCNPhysicsBody(type: .dynamic, shape: SCNPhysicsShape(node: bullet, options: nil))
bullet.physicsBody?.isAffectedByGravity = false
// player.position doesn't do what I thought it would...
let vector = SCNVector3(player.position.x * 100, player.position.y * 100, player.position.z * 100)
bullet.physicsBody?.applyForce(vector, asImpulse: true)
bullet.runAction( SCNAction.sequence([
SCNAction.wait(duration: 5),
SCNAction.removeFromParentNode()]
))
self.sceneView.scene.rootNode.addChildNode(bullet)
虽然我决心找到这个答案,但我想到了一种方法来保持子弹的速度不变,无论两个节点的距离如何。我想在这里提供这个,以防有人遇到类似的问题,但我不想提供这个作为答案 - 因为它仍然使用move(to :)而不是applyForce()。
let bullet = SCNNode(geometry: SCNSphere(radius: 0.1))
bullet.geometry?.firstMaterial?.diffuse.contents = UIColor.green
let enemy = timer.userInfo as! Enemy
bullet.position = enemy.position
bullet.physicsBody = SCNPhysicsBody(type: .dynamic, shape: SCNPhysicsShape(node: bullet, options: nil))
bullet.physicsBody?.isAffectedByGravity = false
bullet.physicsBody?.categoryBitMask = BitMaskCategory.enemyBullet.rawValue
bullet.physicsBody?.contactTestBitMask = BitMaskCategory.player.rawValue
let lineX = playerNode.position.x - bullet.position.x
let lineY = playerNode.position.y - bullet.position.y
let lineZ = playerNode.position.z - bullet.position.z
let distance = sqrtf(lineX*lineX + lineY*lineY + lineZ*lineZ)
let fireBulletAction = SCNAction.move(to: playerNode.position, duration: (TimeInterval(distance / BASE_BULLET_SPEED)))
bullet.runAction(SCNAction.group([
fireBulletAction,
SCNAction.sequence([
SCNAction.wait(duration: 5),
SCNAction.removeFromParentNode()]
)]
))
self.sceneView.scene.rootNode.addChildNode(bullet)