How to make the ball bounce vertically only and not horizontally with SKSpriteKit?

I am making an iOS application in which I want the ball to reflect up and down, rather than horizontally or at a different angle. Unfortunately, the way I decided to develop the game led to some problems in the future. Here is a GIF that shows my problem:

enter image description here

Basically: sometimes, when I click on the pentagon turn, he hits the ball at an angle when I just want him to go up and down.

Here is my ball code:

func createBallNode(ballColor: String) -> SKSpriteNode {
    let ball = SKSpriteNode(imageNamed: ballColor)
    ball.position = CGPoint(x: CGRectGetMidX(frame), y: CGRectGetMidY(frame)+1)

    ball.physicsBody = SKPhysicsBody(circleOfRadius: 25)
    ball.physicsBody?.affectedByGravity = true
    ball.physicsBody?.restitution = 0.99
    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

    return ball
}

In any case, can I adjust the ball so that it always moves in a certain row (vertically)? Does anyone have a design suggestion for the ball, or maybe another way to move it (SKActions, for example: moveTo, not gravity).

Tell me. Thank!

+4
2

node x , SKRange , .

let centerX = ball.position.x
let range = SKRange(lowerLimit:centerX, upperLimit:centerX)

positionX

let constraint = SKConstraint.positionX(range)

, node constraints

ball.constraints = [constraint]

, return ball.

+2

, , , . .

, SKAction :

    let up = SKAction.moveBy(CGVector(dx: 0, dy: 40), duration: 0.3)
    let down = SKAction.moveBy(CGVector(dx: 0, dy: -40), duration: 0.3)
    let upAndDown = SKAction.sequence([up, down])
    let foreverUpDown = SKAction.repeatActionForever(upAndDown)

runAction .

+2

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


All Articles