gpt4 book ai didi

swift - 获取节点最后位置

转载 作者:行者123 更新时间:2023-11-30 11:59:06 24 4
gpt4 key购买 nike

这是我第三次就这个问题寻求帮助。我有一个 SKShapeNode 类型的类名 BallNode。在我的代码中,我还有一个函数,每 3 秒从屏幕顶部生成一个球。现在,我想设置一个函数,每 1 秒定位一次球的位置,因此,如果 ball.position.y > 200 将消息打印到控制台。

这样做的目的是,如果任何球位于这个位置(而不是在它掉落时),我将调用另一个函数。我尝试通过 SKActionupdate(_ currentTime: CFTimeInterval)Timer 但我没有成功,我真的不知道该怎么办...

更新 - 我当前的代码:

var timeType1: CFTimeInterval = 0.0
var timeType2: CFTimeInterval = 2.0

override func update(_ currentTime: CFTimeInterval) {

if (currentTime - timeType1 > timeType2){
print("time")
self.checkBallsPosition()
self.timeType1 = currentTime
}
self.enumerateChildNodes(withName: "color.BallNode") { node, _ in
self.checkBallsPosition()
}
}

func checkBallsPosition() {
self.enumerateChildNodes(withName: "BALL") { (node: SKNode, nil) in
let x = self.createTopBorder()
x.isHidden = true
let wait2 = SKAction.wait(forDuration: 1)
let action2 = SKAction.run {
let position = Double(node.position.y)
if position < 200 {

}
else if position > 200 {
print("bolbo")
node.removeFromParent()
}
}
self.run(SKAction.sequence([wait2,action2]))

}
}

这就是我到目前为止尝试做的事情,正如我所说,问题是我想要将球拿到最后位置。因为球会从屏幕上掉下来,所以最后的位置应该是当它触摸屏幕的底部边框或当它触摸另一个球时。如果我将其设置为“更新”,我会在每一帧或(就像我所做的那样)每秒获取球的位置 - 但不是最后一次。另一个问题是球的位置总是会根据另一个球而改变(当发生碰撞时)。

更新 #2 - 其他功能:

    func spawnBalls() {
let wait = SKAction.wait(forDuration: 3)
let action = SKAction.run {
self.createBall()
}
run(SKAction.repeatForever((SKAction.sequence([wait, action]))))
}

func createBall(){
let ball = BallNode(radius: 65)
print(ball.Name)
print(ball._subName!)

ball.position.y = ((frame.size.height) - 200)
let ballXPosition = arc4random_uniform(UInt32(frame.size.width))
ball.position.x = CGFloat(ballXPosition)
ball.physicsBody?.categoryBitMask = PhysicsCategory.ball
ball.physicsBody?.collisionBitMask = PhysicsCategory.ball
ball.physicsBody?.contactTestBitMask = PhysicsCategory.topBorder
ball.delegate = self
addChild(ball)

}

最佳答案

您没有发布您正在使用的完整代码。不知道你如何生成球、层次结构如何以及如何移动它们,我无法在这里重现它。

我不确定我的理解是否正确,但我相信它可能比你所做的更简单。看看下面的代码是否对您有帮助,我正在使用 SKAction 让球下落(您也可以使用物理来做到这一点),并检查它们何时低于零,何时删除它们。

private let ballSpeed : CGFloat = 400
private let ballRadius : CGFloat = 10

private func spawnBall(atPoint pos : CGPoint){
let b = SKShapeNode(circleOfRadius: ballRadius)
b.name = "ball"
b.position = pos
addChild(b)
b.run(SKAction.moveTo(y: -size.height, duration: TimeInterval((pos.y+size.height)/400)))
}

override func update(_ currentTime: TimeInterval) {
super.update(currentTime)
enumerateChildNodes(withName: "ball") { (node, _) in
if node.position.y < 0 {
node.removeFromParent()
}
}
}

override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
for touch in touches{
let pos = touch.location(in: self)
spawnBall(atPoint: pos)
}
}

关于swift - 获取节点最后位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47462448/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com