我正在制作一个 iOS 应用程序,遇到了一些物理问题。正如您通过下面的 .GIF 可以看出的那样,当我旋转六边形并且球以一定角度撞击矩形时,它失去了一些速度并且不会反弹得那么高。这是因为共享的原因here (主要是因为我限制了球的水平位置,它只在击球角度时使用垂直速度,因此失去了速度)。
我一辈子都想不出解决这个问题的方法。有人有什么想法吗??
Ball节点代码:
func createBallNode(ballColor: String) -> SKSpriteNode {
let ball = SKSpriteNode(imageNamed: ballColor)
ball.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame)+30)
ball.zPosition = 1
ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width/2)
ball.physicsBody?.affectedByGravity = true
ball.physicsBody?.restitution = 1
ball.physicsBody?.linearDamping = 0
ball.physicsBody?.friction = 0
ball.physicsBody?.categoryBitMask = ColliderType.Ball.rawValue
ball.physicsBody?.contactTestBitMask = ColliderType.Rect.rawValue
ball.physicsBody?.collisionBitMask = ColliderType.Rect.rawValue
let centerX = ball.position.x
let range = SKRange(lowerLimit: centerX, upperLimit: centerX)
let constraint = SKConstraint.positionX(range)
ball.constraints = [constraint]
return ball
}
最佳答案
是的,这个问题可能是球没有完全“对齐”时击中六边形造成的。在这种情况下,球失去垂直速度以支持水平轴。
既然你想要一个“离散逻辑”,我相信在这种情况下你应该避免物理(至少对于弹跳部分)。重复垂直移动球的 SKAction
会容易得多。
例子
我准备了一个简单的例子
class GameScene: SKScene {
override func didMove(to view: SKView) {
super.didMove(to: view)
let ball = createBallNode()
self.addChild(ball)
}
func createBallNode() -> SKSpriteNode {
let ball = SKSpriteNode(imageNamed: "ball")
ball.position = CGPoint(x: frame.midX, y: frame.minY + ball.frame.height / 2)
let goUp = SKAction.move(by: CGVector(dx: 0, dy: 600), duration: 1)
goUp.timingMode = .easeOut
let goDown = SKAction.move(by: CGVector(dx: 0, dy: -600), duration: 1)
goDown.timingMode = .easeIn
let goUpAndDown = SKAction.sequence([goUp, goDown])
let forever = SKAction.repeatForever(goUpAndDown)
ball.run(forever)
return ball
}
}
更新
如果您需要在每次球接触六边形底部时执行检查,您可以使用此代码
class GameScene: SKScene {
override func didMove(to view: SKView) {
super.didMove(to: view)
let ball = createBallNode()
self.addChild(ball)
}
func createBallNode() -> SKSpriteNode {
let ball = SKSpriteNode(imageNamed: "ball")
ball.position = CGPoint(x: frame.midX, y: frame.minY + ball.frame.height / 2)
let goUp = SKAction.move(by: CGVector(dx: 0, dy: 600), duration: 1)
goUp.timingMode = .easeOut
let goDown = SKAction.move(by: CGVector(dx: 0, dy: -600), duration: 1)
goDown.timingMode = .easeIn
let check = SKAction.customAction(withDuration: 0) { (node, elapsedTime) in
self.ballTouchesBase()
}
let goUpAndDown = SKAction.sequence([goUp, goDown, check])
let forever = SKAction.repeatForever(goUpAndDown)
ball.run(forever)
return ball
}
private func ballTouchesBase() {
print("The ball touched the base")
}
}
正如您现在看到的,每次球处于较低的 y 坐标时,方法 ballTouchesBase
都会被调用。这是为六边形的颜色添加检查的正确位置。
关于ios - SKSpriteNode 在碰撞时失去速度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39211457/