我的目的是在一个场景中随机移动一个边界区域内的居民,每3秒改变SCNVector3的x、y、z位置,然后将节点移动到这些点。每3秒改变SCNVector3的x、y和z位置,然后节点移动到这些点。
我遇到的问题是节点没有移动到这些点。这些点的变化可以在 print("running: x\(self.x) y\(self.y) z\(self.z) on - \(node.name!)")
行。我假设 SCNAction.move(to:)
动作被调用,但不知为什么这一行什么也没做。
没有抛出任何错误,节点只是在随机的点上产卵,从未移动。
这是我实现当前运动的代码。
var x = Float.random(in: -0.25...0.265)
var y:Float = 0
var z = Float.random(in: -0.3...0.215)
func spawnInhabitants() {
let type = skyBalls[_index].getInhabitantType().rawValue
let scene = SCNScene(named: "art.scnassets/inhabitants/\(type).scn")!
let inhabitantNode:SCNNode = scene.rootNode.childNode(withName: type, recursively: false)!
inhabitantNode.scale = SCNVector3(0.000075, 0.000075, 0.000075)
inhabitantNode.physicsBody?.physicsShape = SCNPhysicsShape(node: inhabitantNode)
inhabitantNode.physicsBody?.type = .dynamic
inhabitantNode.physicsBody?.isAffectedByGravity = false
inhabitantNode.physicsBody?.categoryBitMask = 1
inhabitantNode.physicsBody?.collisionBitMask = 6
inhabitantNode.physicsBody?.contactTestBitMask = 1
for inhab in skyBalls[_index].getInhabitants() {
x = Float.random(in: -0.25...0.265)
y = 0
z = Float.random(in: -0.3...0.215)
inhabitantNode.position = SCNVector3(x, y, z)
let move_around = SCNAction.run { node in
self.x = Float.random(in: -0.25...0.265)
self.y = 0
self.z = Float.random(in: -0.3...0.215)
print("running: x\(self.x) y\(self.y) z\(self.z) on - \(node.name!)")
}
let move = SCNAction.move(to: SCNVector3(x, y, z), duration: 3) //<- This is the problem
let seq = SCNAction.sequence([move_around, move])
let i = skyBalls[_index].getInhabitants().firstIndex(of: inhab)
inhabitantNode.name = "\(type)\(i!)"
inhabitantNode.runAction(SCNAction.repeatForever(seq))
colonyScene.rootNode.addChildNode(inhabitantNode.copy() as! SCNNode)
}
}
作为一个说明:
skyBalls[_index].getInhabitantType().rawValue
^返回一个居民的枚举类型的字符串(主要用于命名)
skyBalls[_index].getInhabitants()
返回skyBalls实例中的居民列表和一个索引,更确切地说,是居民的数组。
colonyScene
^这是视图的SCNScene。
先谢谢你。
你的移动动作可能在创建动作时使用x、y、z值。所以你可以尝试在生成随机值后,在运行动作内部创建一个新的动作......。(我简化了你的代码片段来测试这种方法)
for inhab in skyBalls {
inhab.position = SCNVector3(x, y, z)
let move_around = SCNAction.run { node in
self.x = Float.random(in: -0.25...0.265)
self.y = 0
self.z = Float.random(in: -0.3...0.215)
print("running: x\(self.x) y\(self.y) z\(self.z) on - \(node.name)")
let moveAction = SCNAction.move(to: SCNVector3(self.x, self.y, self.z), duration: 3)
node.runAction(moveAction)
}
let wait = SCNAction.wait(duration: 3) // make same as moveAction duration
//let move = SCNAction.move(to: SCNVector3(x, y, z), duration: 3) //<- This is the problem
let seq = SCNAction.sequence([move_around, wait])
inhab.runAction(SCNAction.repeatForever(seq))
scnView.scene!.rootNode.addChildNode(inhab)
}
希望能帮到你