I know there are a couple other questions regarding this but none of them seem to work or they all are incomplete or half complete. I need to know how to keep an object within the visible screen! So I have a spaceship sprite that uses the device's tilt and core motion to fly across the screen. If I tilt my device, the spaceship will at one point leave my screen and continue going in that direction. How do I keep the spaceship stay inside my screen so that even if I tilt to the left or right it will never leave the visible screen? Here is some of my code to the spaceship.
class GameScene: SKScene, SKPhysicsContactDelegate {
var ship = SKSpriteNode(imageNamed:"Spaceship")
let manager = CMMotionManager()
override func didMoveToView(view: SKView) {
/* Setup your scene here */
ship.xScale = 1/5
ship.yScale = 1/5
ship.position = CGPoint(x: self.frame.width/(2), y: self.frame.height/1.5)
self.physicsWorld.contactDelegate = self
manager.startAccelerometerUpdates()
manager.accelerometerUpdateInterval = 0.1
manager.startAccelerometerUpdatesToQueue(NSOperationQueue.mainQueue()){
(data, error) in
self.physicsWorld.gravity = CGVectorMake(CGFloat((data?.acceleration.x)! * 15), CGFloat((data?.acceleration.y)! * 15))
}
ship.physicsBody = SKPhysicsBody()
ship.physicsBody?.affectedByGravity = true
self.addChild(ship)
}
I already tried self.view?.bounds and making it into a physics body but my spaceship never comes into contact with it.
All I had to do was meddle around with the size of the screen in the .sks file. I specifically made mine 800x640 because I am testing on an I-Pod 5. Then I added this bit of code:
let edgeFrame = CGRect(origin: CGPoint(x: ((self.view?.frame.minX)! + 200) ,y: (self.view?.frame.minY)!), size: CGSize(width: (self.view?.frame.width)! + 90, height: (self.view?.frame.height)! + 90))
self.physicsBody = SKPhysicsBody(edgeLoopFromRect: edgeFrame)
This made a proper boundary around my screen and did not allow my spaceship to leave the screen. Best of all this was a perfect fit so if you are testing on a different device then just adjust the width and height numbers as needed. Remember to also adjust your .sks screen size.
Credits to 0x141E for hinting me in the right direction.
Related
I am making a game in Swift using spritekit and I want 2 objects on screen, one that I move with the touchesMoved function (player) and the other to stay still in its position in the screen (cell).
I wanted to make the objects physicsbody's so that I could work out collisions between them, but now whenever the scene loads the objects fall straight away. And the object moved through touch falls as soon as the user stops touching the screen.
Here's all of the code relating to the object that should stay stationary in the scene and I am unsure what makes it fall.
//Defining the cell
let cell = SKSpriteNode(imageNamed: "cell.png")
override func didMove(to view: SKView){
self.physicsWorld.contactDelegate = self
cell.physicsBody?.categoryBitMask = cellCategory
cell.physicsBody?.contactTestBitMask = playerCategory
cell.physicsBody?.isDynamic = true
cell.physicsBody = SKPhysicsBody(rectangleOf: cell.frame.size)
//Adding the cell to the scene
cell.position = CGPoint(x:size.width * 0.9, y:size.height * 0.9)
cell.size = CGSize(width: 50, height: 50)
addChild(cell)
Any help in what makes the object fall and how I can stop it from happening would be greatly appreciated.
Gravity is by default on. You can either turn it off entirely by setting the gravity property of the scene's physicsWorld:
// somewhere in the scene's initialization, or in didMove if you like
physicsWorld.gravity = CGVector(dx: 0.0, dy: 0.0)
See https://developer.apple.com/documentation/spritekit/skphysicsworld for info on that.
Or you can turn off whether individual objects are affected by gravity. E.g.,
let body = SKPhysicsBody(circleOfRadius: 10.0)
body.affectedByGravity = false
See https://developer.apple.com/documentation/spritekit/skphysicsbody, and in particular, https://developer.apple.com/documentation/spritekit/skphysicsbody/1519774-affectedbygravity
You have a different problem in that you're setting the properties of your cell's physics body before you're creating it. cell.physicsBody?... = will not assign anything until cell.physicsBody exists. So those assignments must be moved after you create cell.physicsBody = SKPhysicsBody(rectangleOf: ...)
I'm having a hard time setting boundaries and positioning camera properly inside my view after panning. So here's my scenario.
I have a node that is bigger than the screen and I want to let user pan around to see the full map. My node is 1000 by 1400 when the view is 640 by 1136. Sprites inside the map node have the default anchor point.
Then I've added a camera to the map node and set it's position to (0.5, 0.5).
Now I'm wondering if I should be changing the position of the camera or the map node when the user pans the screen ? The first approach seems to be problematic, since I can't simply add translation to the camera position because position is defined as (0.5, 0.5) and translation values are way bigger than that. So I tried multiplying/dividing it by the screen size but that doesn't seem to work. Is the second approach better ?
var map = Map(size: CGSize(width: 1000, height: 1400))
override func didMove(to view: SKView) {
(...)
let pan = UIPanGestureRecognizer(target: self, action: #selector(panned(sender:)))
view.addGestureRecognizer(pan)
self.anchorPoint = CGPoint.zero
self.cam = SKCameraNode()
self.cam.name = "camera"
self.camera = cam
self.addChild(map)
self.map.addChild(self.cam!)
cam.position = CGPoint(x: 0.5, y: 0.5)
}
var previousTranslateX:CGFloat = 0.0
func panned (sender:UIPanGestureRecognizer) {
let currentTranslateX = sender.translation(in: view!).x
//calculate translation since last measurement
let translateX = currentTranslateX - previousTranslateX
let xMargin = (map.nodeSize.width - self.frame.width)/2
var newCamPosition = CGPoint(x: cam.position.x, y: cam.position.y)
let newPositionX = cam.position.x*self.frame.width + translateX
// since the camera x is 320, our limits are 140 and 460 ?
if newPositionX > self.frame.width/2 - xMargin && newPositionX < self.frame.width - xMargin {
newCamPosition.x = newPositionX/self.frame.width
}
centerCameraOnPoint(point: newCamPosition)
//(re-)set previous measurement
if sender.state == .ended {
previousTranslateX = 0
} else {
previousTranslateX = currentTranslateX
}
}
func centerCameraOnPoint(point: CGPoint) {
if cam != nil {
cam.position = point
}
}
Your camera is actually at a pixel point 0.5 points to the right of the centre, and 0.5 points up from the centre. At (0, 0) your camera is dead centre of the screen.
I think the mistake you've made is a conceptual one, thinking that anchor point of the scene (0.5, 0.5) is the same as the centre coordinates of the scene.
If you're working in pixels, which it seems you are, then a camera position of (500, 700) will be at the top right of your map, ( -500, -700 ) will be at the bottom left.
This assumes you're using the midpoint anchor that comes default with the Xcode SpriteKit template.
Which means the answer to your question is: Literally move the camera as you please, around your map, since you'll now be confident in the knowledge it's pixel literal.
With one caveat...
a lot of games use constraints to stop the camera somewhat before it gets to the edge of a map so that the map isn't half off and half on the screen. In this way the map's edge is showing, but the furthest the camera travels is only enough to reveal that edge of the map. This becomes a constraints based effort when you have a player/character that can walk/move to the edge, but the camera doesn't go all the way out there.
I am working with SpriteKit right now and I came across a problem that seems simple but I couldn't find anything on the internet. I have three buttons that are shaped like parallelograms stacked on top of each other and it looks like this:
Screenshot of buttons
let button = SKSpriteNode(imageNamed: "playbutton")
let leaderButton = SKSpriteNode(imageNamed: "leaderbutton")
let homeButton = SKSpriteNode(imageNamed: "homebutton")
button.position = CGPoint(x: size.width/2, y: size.height/2)
addChild(button)
leaderButton.position = CGPoint(x: size.width/2, y: size.height/2 - button.size.height/2)
addChild(leaderButton)
homeButton.position = CGPoint(x: size.width/2, y: size.height/2 - button.size.height)
addChild(homeButton)
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if button.containsPoint(location) {
button.runAction(SKAction.scaleTo(0.8, duration: 0.1))
}
else if leaderButton.containsPoint(location) {
leaderButton.runAction(SKAction.scaleTo(0.8, duration: 0.1))
}
else if homeButton.containsPoint(location) {
homeButton.runAction(SKAction.scaleTo(0.8, duration: 0.1))
}
}
}
This is how I am detecting touches. The problem is that they overlap because the sprite is actually a rectangle so when i try and tap on the top left of the second button, the top button detects it. I was wondering of there is a way to detect touch only in the texture like how you can set the physics body to a texture.
Thanks for any help you can give me!
Link works now.
So I tried this:
button.position = CGPoint(x: size.width/2, y: size.height/2)
button.physicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "playbutton"), size: button.size)
button.physicsBody?.dynamic = false
addChild(button)
leaderButton.position = CGPoint(x: size.width/2, y: size.height/2 - button.size.height/2)
leaderButton.physicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "leaderbutton"), size: leaderButton.size)
leaderButton.physicsBody?.dynamic = false
addChild(leaderButton)
homeButton.position = CGPoint(x: size.width/2, y: size.height/2 - button.size.height)
homeButton.physicsBody = SKPhysicsBody(texture: SKTexture(imageNamed: "homebutton"), size: homeButton.size)
homeButton.physicsBody?.dynamic = false
addChild(homeButton)
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
for touch: AnyObject in touches {
let location = touch.locationInNode(self)
if physicsWorld.bodyAtPoint(location)?.node == button {
button.runAction(SKAction.scaleTo(0.8, duration: 0.1))
print("play")
}
if physicsWorld.bodyAtPoint(location)?.node == leaderButton {
leaderButton.runAction(SKAction.scaleTo(0.8, duration: 0.1))
print("leader")
}
if physicsWorld.bodyAtPoint(location)?.node == homeButton {
homeButton.runAction(SKAction.scaleTo(0.8, duration: 0.1))
}
}
}
It still registers the full frame and not just the physics body. See the link to see the buttons and how their coordinates intersect.
If you attach a physics body to each button, you can detect which physics body your touch lands on.
You can generate a physics body from the button's texture (assuming the button is an SKSpriteNode) using SKPhysicsBody(texture:size:) or SKPhysicsBody(texture:alphaThreshold:size:), or you can create a CGPath describing the button's shape and use SKPhysicsBody(polygonFromPath:). Assign the body to the button's physicsBody property. Assuming you don't actually want the physics simulator to move your buttons, set each body's dynamic property to false.
Then you can use physicsWorld.bodyAtPoint(_:) to get one of the bodies that a touch lands on (where physicsWorld is a property of your SKScene). Use the body's node property to get back to the button node. If bodies overlap, bodyAtPoint returns an arbitrary body.
You can use physicsWorld.enumerateBodiesAtPoint(_:usingBlock:) if you need all of the bodies that your touch lands on.
A completely different approach, if you can create a CGPath describing the button's shape, is to use SKScene.convertPointFromView(_:) and then SKNode.convertPoint(_:fromNode:_) to convert the point into the button's coordinate system, and then use CGPathContainsPoint (a global function) to detect whether the point is in the path describing the button shape.
(I can't see your imgur link, but I think I have a pretty good idea of what you're describing.)
There are some discussions on how to read the alpha value of out an SKTexture, but those require quite a bit of overhead for just "did I touch a parallelogram"? Especially if you add alpha effects to your buttons.
You can do whatever logic you want on the location - you have a CGPoint that contains the location, and you know the size and shape of your buttons.
It should be pretty straightforward to write a function to test whether a point is inside a parallelogram-shaped button. Since parallelograms are basically rectangles with triangles on each end of an "inner" rect, if you know the size of that "inner" rect, you can pretty easily determine whether the touch is where you want by:
Checking that it's in the rect of the entire button. If not, you know it's not in the parallelogram.
Checking to see if it's inside the "inner" rectangle - the part of the parallelogram with the triangles "chopped off" the ends. If so, then you know it's in the parallelogram.
Checking to see if it's inside one of the triangles. You know how far up and how far across the touch is in the rect that contains the triangle, and you know the slope of the line that divides that rect to make the triangle by virtue of its width and height. That makes it trivial to check whether the point is in the triangle or not - just use the "y=mx+b" formula for a line, where m is the slope and b is whatever you need to add to get the line to pass through the corner of the rect (typically your "y intercept"). If the y coordinate is less than/greater than m*(the x coordinate) + b, you can determine whether the touch is inside or outside that triangle.
Once you have that function, you can use it as the test for checking each button.
I am building a ios game with swift and I have run into a bit of a problem. I am trying to spawn balls from the top of the screen and have them come down towards the ground. They are supposed to have random x values and go down at random rates but instead of spawning on the screen the nodes spawn on an x value which is not encompassed by the screen. Please help me as I think I have done everything right.
Here is the code for my addball function...
func addBall(){
//create ball sprite
var ball = SKSpriteNode(imageNamed: "ball.png")
//create physics for ball
ball.physicsBody = SKPhysicsBody(rectangleOfSize: ball.size) // 1
ball.physicsBody?.dynamic = true // 2
ball.physicsBody?.categoryBitMask = PhysicsCategory.Ball // 3
ball.physicsBody?.contactTestBitMask = PhysicsCategory.Person & PhysicsCategory.Ground
ball.physicsBody?.collisionBitMask = PhysicsCategory.None // 5
//generate random postion along x axis for ball to spawn
let actualX = random(min:ball.frame.size.width/2+1, max: self.frame.size.width - ball.frame.size.width/2-1)
println(actualX)
//set balls positon
ball.position = CGPoint(x: actualX, y: size.height - ball.size.width/2)
//add ball to scene
addChild(ball)
//determine speed of ball
let actualDuration = random(min: CGFloat(3.0), max: CGFloat(5.0))
//create movement actions
let actionMove = SKAction.moveTo(CGPoint(x:actualX, y: -ball.size.width/2), duration: NSTimeInterval(actualDuration))
let actionMoveDone = SKAction.removeFromParent()
ball.runAction(SKAction.sequence([actionMove, actionMoveDone]), withKey: "action")
}
here is the code for my random functions
func random() -> CGFloat {
return CGFloat(Float(arc4random()) / 0xFFFFFFFF)
}
func random(#min: CGFloat, max: CGFloat) -> CGFloat {
return random() * (max - min) + min
}
The problem here is that your SKScene likely takes up much more space than the screen of your device. Thus, when you calculate a random value using the whole scene, some of the time the ball will spawn in the area of the scene not visible to you.
The two main properties that control the scene's size are its size and scaleMode properties. The scaleMode property relates to how the scene is mapped. Unless you initialized and presented this scene yourself, you can check the scaleMode in your view controller. It will likely be set to aspectFill, which according to Apple means:
The scaling factor of each dimension is calculated and the larger of the two is chosen. Each axis of the scene is scaled by the same scaling factor. This guarantees that the entire area of the view is filled but may cause parts of the scene to be cropped.
If you don't like this, there are other scaleModes. However, in most cases this mode would actually be preferable since SpriteKit's internal scaling is able to make universal apps. If this is fine for you, then the easiest thing to do is set hardcoded values for something like the spawn locations for your ball node.
I'm looking for the proper SpriteKit way to handle something of a scrollable world. Consider the following image:
In this contrived example, the world boundary is the dashed line and the blue dot can move anywhere within these boundaries. However, at any given point, a portion of this world can exist off-screen as indicated by the image. I would like to know how I can move the blue dot anywhere around the "world" while keeping the camera stationary on the blue dot.
This is Adventure, a sprite kit game by apple to demonstrate the point I made below. Read through the docs, they explain everything
Theres a good answer to this that I can't find at the moment. The basic idea is this:
Add a 'world' node to your scene. You can give it a width/height that is larger than the screen size.
When you 'move' the character around (or blue dot), you actually move your world node instead, but in the opposite direction, and that gives the impression that you're moving.
This way the screen is always centered on the blue dot, yet the world around you moves
below is an example from when I was experimenting a while ago:
override func didMoveToView(view: SKView) {
self.anchorPoint = CGPointMake(0.5, 0.5)
//self.size = CGSizeMake(600, 600)
// Add world
world = SKShapeNode(rectOfSize: CGSize(width: 500, height: 500))
world.fillColor = SKColor.whiteColor()
world.position = CGPoint(x: size.width * 0.5, y: size.height * 0.5)
world.physicsBody?.usesPreciseCollisionDetection = true
self.addChild(world)
}
override func update(currentTime: CFTimeInterval) {
world.position.x = -player.position.x
world.position.y = -player.position.y
}
override func didSimulatePhysics() {
self.centerOnNode(self.camera)
}
func centerOnNode(node: SKNode) {
if let parent = node.parent {
let nodePositionInScene: CGPoint = node.scene!.convertPoint(node.position, fromNode: parent)
parent.position = CGPoint(
x: parent.position.x - nodePositionInScene.x,
y: parent.position.y - nodePositionInScene.y)
}}
If you create a "camera" node which you add to your "world" node, a couple of simple functions (above) allow you to "follow" this camera node as it travels through the world, though actually you are moving the world around similar to Abdul Ahmad's answer.
This method allows you to use SpriteKit functionality on the camera. You can apply physics to it, run actions on it, put constraints on it, allowing effects like:
camera shaking (an action),
collision (a physics body, or matching the position of another node with a physics body),
a lagging follow (place a constraint on the camera that keeps it a certain distance from a character, for example)
The constraint especially adds a nice touch to a moving world as it allows the "main character" to move around freely somewhat while only moving the world when close to the edges of the screen.