Reputation: 119
I added the following in didMoveToView
:
var ground = SKNode()
ground.position = CGPointMake(0, 0)
ground.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
ground.physicsBody?.dynamic = false
ground.physicsBody?.friction = 1
self.addChild(ground)
and in the touchesBegan
, I added the following :
mainChar.physicsBody?.velocity = CGVectorMake(0, 0)
mainChar.physicsBody?.applyImpulse(CGVectorMake(85, 0))
Where mainChar is a SKSpriteNode that was defined earlier. I tested the above code by changing the direction of the applyImpulse in the y direction and saw that the mainChar does not go beyond the top of the screen. However when I leave it as 85 or change it to -85, it disappears from both the right and left hand side of the screen.
What can I do differently to make sure that the mainChar stays within the bonding box of the screen?
Thanks.
Upvotes: 0
Views: 1510
Reputation: 3812
Odds are your scene isn't the same size as your frame and you are using .AspectFill
.
If you turn on physics debugging you will notice you have a green line on either top and bottom or left and right.
skView.showsPhysics = true
If you do this...
scene.scaleMode = .AspectFit
Everything will likely magically work but you will notice some black bars
If you print in your didMoveToView (if .AspectFill)
println("\(self.frame)")
println("\(view.frame)")
You will likely see that you are trying to fit a really big scene into a small view. Your scene gets scaled down into your view, but the size remains the same. This causes some things to get cut off (even your ground node) You will have to do some math to figure out what is getting cut off on the top and bottom. After that you will need to create a frame based on that and offset your node.
Sorry I couldn't do the math for you, but thought if I at least get you pointed in the right direction and you know why then you might figure out the rest.
Upvotes: 1
Reputation: 20284
Setting dynamic as false prevents the node from being affected by collisions.
Change your code as follows:
var ground = SKNode()
ground.position = CGPointMake(0, 0)
ground.physicsBody = SKPhysicsBody(edgeLoopFromRect: self.frame)
ground.physicsBody?.dynamic = true //This should be set to true
ground.physicsBody?.affectedByGravity = false
ground.physicsBody?.friction = 1
self.addChild(ground)
You will also have to set the categories for each physicsBody.
Upvotes: 0