I am making an iOS application in which I only want the ball to bounce up & down, not horizontally or by any other angle. Unfortunately, the way I decided to design the game led to some problems down the road. Here is a GIF that kind of shows what my problem is:
Basically: sometimes when I click to rotate the pentagon, it hits the ball at an angle when I only want it going up and down.
Here is my code for the ball:
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
}
Is there anyway I can design the ball to always move in a certain line (vertically)? Does anyone have design suggestions for the ball, or maybe a different way of moving it (SKActions, ex: moveTo rather than using gravity).
Let me know. Thanks!
To restrict a node's x-coordinate to a fixed value, define an SKRange
with the minimum and maximum parameters set to the same value.
let centerX = ball.position.x
let range = SKRange(lowerLimit:centerX, upperLimit:centerX)
From the range, define a positionX
constraint
let constraint = SKConstraint.positionX(range)
Lastly, add the constraint to node's constraints
array
ball.constraints = [constraint]
This should work with your existing code if you add it above the return ball
statement.
The ball bounces irregularly because when you are moving the sides of the pentagon, the ball touches a tiny little bit of side and changes its trajectory. That's how gravity works.
If you want to bounce the ball your way, use SKAction
s like this:
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)
And just call runAction
on the ball.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With