SKSpriteKit maintains constant speed after a collision

I'm trying to make my first iOS app and am currently facing a problem.

In my game, when the ball bounces, I want it to recover to the same height and speed. This is all fine now. However, when I rotate the hexagon and it falls at an angle, it ends the rate of loss, rather than bouncing to the same height.

So my question is: how to get the ball to maintain the same speed in a collision?

Here is the code for my node 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
}

The following is a GIF explaining the problem in visual form: enter image description here

0
source share
1 answer

, , . , .

- didSimulatePhysics , , . , , .

let neededVelocity = sqrt(2 * physicsWorld.gravity.dy * (intendedHeight - ball.posiiton.y))
if ball.physicsBody.velocity.dy < neededVelocity && ball.physicsBody.velocity.dy > 0 {
    ball.physicsBody.velocity = CGVector(dx: 0, dy: neededVelocity)
}
+1

Source: https://habr.com/ru/post/1652899/


All Articles