Giving physics to tiles of SKTileMapNode in Xcode 8 - swift

I am learning Swift, and as a project I am working on a tile based 2D game similar to super mario where my character will walk and jump on tiles.
The latest version of Xcode and Sprite Kit give the ability to create a Tile Map directly in Xcode.
In the presentation of the new Xcode and Sprite kit, the guy demonstrates a game similar to what i am working on.
https://developer.apple.com/videos/play/wwdc2016/610/ (around the 20th minute).
He mentions giving Tiles user data properties which i did, and in code we search through all the tiles which have that user data and give them some physics properties so that the character can collide or interact with them (in my case, my character not falling or walking through the tiles).
so basically, the idea is giving those tiles a physics Body, but this can't be done using SKphysicsBody. So there must be another way, and since i am new to Swift i am missing it.
if anyone knows this, i would very much appreciate the help.
If the question is unclear let me know because i am also new to stack overflow.

Apple staff member Bobjt says here that "the right approach" is to add user data to your SKTileDefinition objects and use that to identify and add physics bodies to your tiles.
So you would add a user data value to a tile definition either programmatically or in the editor, like so:
Then in code you would check each tile definition to see if it has the user data value. If so, then you need to calculate the tile's position and add a physics body on a new node, parenting it to your tile map. Here is the code for this which Bobjt referred to as "the correct approach":
self.tileMap = self.childNode(withName: "Tile Map") as? SKTileMapNode
guard let tileMap = self.tileMap else { fatalError("Missing tile map for the level") }
let tileSize = tileMap.tileSize
let halfWidth = CGFloat(tileMap.numberOfColumns) / 2.0 * tileSize.width
let halfHeight = CGFloat(tileMap.numberOfRows) / 2.0 * tileSize.height
for col in 0..<tileMap.numberOfColumns {
for row in 0..<tileMap.numberOfRows {
let tileDefinition = tileMap.tileDefinition(atColumn: col, row: row)
let isEdgeTile = tileDefinition?.userData?["edgeTile"] as? Bool
if (isEdgeTile ?? false) {
let x = CGFloat(col) * tileSize.width - halfWidth
let y = CGFloat(row) * tileSize.height - halfHeight
let rect = CGRect(x: 0, y: 0, width: tileSize.width, height: tileSize.height)
let tileNode = SKShapeNode(rect: rect)
tileNode.position = CGPoint(x: x, y: y)
tileNode.physicsBody = SKPhysicsBody.init(rectangleOf: tileSize, center: CGPoint(x: tileSize.width / 2.0, y: tileSize.height / 2.0))
tileNode.physicsBody?.isDynamic = false
tileNode.physicsBody?.collisionBitMask = playerCollisionMask | wallCollisionMask
tileNode.physicsBody?.categoryBitMask = wallCollisionMask
tileMap.addChild(tileNode)
}
}
}
Personally, I think this approach is too fussy. I'm going to try a different approach in my game and if it works I'll post it here. What I'd really like is for Apple to enhance the tile map API so that we can add physics bodies directly to individual tiles. Maybe in the process they could optimize the engine so that physics bodies on individual tiles would be automatically merged to form larger, more optimal shapes in order to improve system performance.
Update: I filed a request with Apple about this issue, for whatever good might come of it.

I'm not sure there's a surefire way to do this yet... but here's two ways to think about how to try apply physics to a tilemap.
Option 1: Apply SKNodes to each positions of each tile on your map, and apply an appropriate physicsbody to that SKNode based on the content and state of that tile.
Option 2: Use the position information of each tile to add an array of physicsbodies to the SKTileMapNode, and position each of them accordingly.
I'm imagining a gravity down, Mario style platformer, with this kind of terrain in need of physics bodies for the ground:
Lifted transcript from Apple's WWDC about tiles and physics:
And you'll note that I'm colliding with the tiles here.
And I achieve this by leveraging custom user data that we can put on
each of our tiles.
Here, I'll show you in our tile set.
Select one of the variants here.
And you can see that we have some user data over here.
And I just have a value called edgeTile which is a Boolean, and I set
to 1.
So, in code, I'm going through the tile map in our platform demo here,
and I'm looking for all of these edge tiles.
And whenever I find one, I create some physics data to allow the
player to collide with it.
And since it is just in our tile map here, say I wanted to get over
this large wall here.
When I run the game, you'll see that my guy can't actually jump high
enough to get over it.
And he really wants to because that red button over there looks really
tempting.
I really want to push that thing.
So, since we're just generating our physics data from our tiles and
our user data, all we can do is just going here and erase these tiles
and build and run our game again.
The tiles are now gone and we can now move through there.
And we didn't have to change code or anything.
We just used the data that we pulled from the tile map to set up our
tile.
It's that simple.
Makes it sound very simple, but takes a far greater mind than mine to figure out what is being done, and how it's being done.

Alternatively, you can apply a line sweep algorithm to the tiles you want to give a SKPhysicsBody.
You can do this in four steps;
Iterate through the position of the tiles in your SKTileMap.
Find the tiles that are adjacent to one another.
For each group of adjacent tiles, collect:
a down-left corner coordinate and
an up-right corner coordinate.
Draw a square, and move on to the next group of tiles until you run out of tile coordinates.
Screenshot without visuals for comparison
Screenshot without visuals showing the physicsbodies
See my answer in a similar post on how to implement this.

I spent two days trying different ideas but could find nothing better than what I posted in my other answer. As mentioned there, it is the way recommended by an Apple staff member and as far as I know it's the most efficient way to have SpriteKit automatically add physics bodies to all your tiles. I've tested it and it works. (Although I'm still holding my breath for Apple to add a straightfoward way of putting physics bodies on tiles).
But there are other considerations. If you are having performance issues because there are too many physics bodies in your scene, you might want to try one of these other approaches. However, they are both more time-consuming than the approach described above. The only reason that may justify using one of these more labor-intensive approaches is if you need to reduce the number of physics bodies in your scene due to performance issues. Otherwise, I think the "automatic" approach mentioned above is the best option we have.
So I won't go into detail here because I think the automatic option is the best. These are just ideas for alternate approaches if your game needs to be extra stingy with system resources.
Alternate Approach #1 - Use Fewer Physics Bodies
Create your tile map in the editor. Then keep working in the editor to drag Color Sprites (SKSpriteNodes) over parts of your map that need a physics body. Shape the nodes to make the largest rectangle possible for areas that need physics bodies. This works best for for large, flat surfaces like walls, floors, ceilings, platforms, crates, etc. It's tedious but you end up with far fewer physics bodies in your simulation than if you had used the automatic approach mentioned above.
Alternate Approach #2 - Use No Physics Bodies
This idea would probably require even more work, but you could potentially avoid using physics bodies altogether. First, create your tile map in the editor. Analyze your map to identify which tiles mark a barrier, beyond which the player should not cross. Assign a user data identifier to that type of tile. You would need different categories of identifiers for different types of barriers, and you may also need to design your artwork to fit this approach.
Once your barrier tiles are sufficiently identified, write code which checks the user data value for the tile currently occupied by the player sprite and restrict the sprite's movement accordingly. For example, if the player enters a title that marks an upper boundary, your movement code would not allow the player sprite to move up. Likewise, if the player enters a tile that marks the leftmost boundary, your movement code will not let the player travel left.

Related

Unity - Tilemap Contains - how to read if Tilemap contains a tile on a specific coordinate in world?

I'm a complete noob in gamedev, but I've watched a number of videos on generating a 2D array to setup Grid-based combat (pathing, obstacles etc), and I don't find the programmable approach intuitive or visually friendly.
Is it possible to setup such level with obstacles using multiple tilemaps?
1st tilemap would include the whole level zone (I named it "General Tilemap"):
2nd tilemap would only contain tiles that would be marked as collision when being read (I named it "Collision Tilemap") and player wouldn't be able to move to them:
My logic would be to read the adjacent tiles around the player, and if:
A tile exists on the General tilemap, but not on the Collision tilemap, player can click it and move there.
A tile exists on both tilemaps, it is marked as collision, it cannot be clicked.
A tile doesn't exist, it is out of boundaries, it cannot be clicked.
Could you please let me know if this is a valid approach (for smaller levels at least, I won't be making anything large so scalability is not an issue), or have I gone completely off course and there's a superior way to do this properly?
I'm currently stuck at the very first step - reading whether the tile on a coordinate (next to player) is existing or null for both tilemaps. Doing my best to figure it out though.
Thanks!
Managed to check if tilemap contains a tile on xy coordinates in Start function, by finding the relevant Tilemap and using hasTile to read it it has value or not. This returns a boolean.
Tilemap generalTilemap = GameObject.Find("General Tilemap").GetComponent<Tilemap>();
hasGTile = generalTilemap.HasTile(playerTileCoord);
Still not sure if this approach will work for me long-term, especially when I get to the pathfinding algorithm, but we'll see!

Swift SKSpriteNode: Chaining Sprites by Image Feature

Context
For the purpose of a MWE we will be using the following image of a stick figure:
with the goal of having a chain of these sprites move, hand-in-hand, across the screen:
It is worthwhile to note that the stick figure image itself is wider than the arm-span of this stick figure. The background is, however, transparent.
Depending on the application, one may make a class that either inherits from SKSpriteNode or encapsulates it, e.g. a class called Person, to store additional information, where there may be an array var people = [Person]().
Questions
1.) Suppose you had two instances of the aforementioned Person class with each sprite taking a stick figure image. How could one position them - programmatically - such that the sprites are touching ''hand in hand'' although the image has a transparent background? Of course one could spend some time fiddling about to get find a spacing parameter to ensure this is achieved, but that parameter would always have to be, via trial-and-error, re-calculated if the sprites were re-scaled.
2.) Given a chain of these sprites, hand in hand, how could one animate them to move across the screen at the same velocity? If one calculates the spacing parameter alluded to in 1.) then an SKAction could be given to each Person such that their end position is offset (but total distance traveled is the same), where the TimeInterval is maintained the same. Is there a way to tell all the sprites to move to the left until off the screen at a rate of $x$ pixels per second?
It looks like you've mostly answered your own questions already, but here are some additional ideas:
Make the spacing value proportional to the size of the sprite.
Yes, there is an SKAction that moves a sprite a given distance over a given period of time (effectively a velocity): let moveAction = SKAction.moveBy(x: 10, y: 0, duration: 2)

Detect touches on SKSpriteNode with oddly shaped image(s) running animations

Using SpriteKit for an iOS 9.0 app/game (and no physics body).
I have a few SpriteNodes on a scene. SpriteNodes are with oddly shaped images and runs through multiple frames for animation.
What is the best way to detect touches on a SpriteNode's image content, but not on transparent area of the entire image rectangle.
I see a lot of posts on using SKCropNode / MaskImage. In my scenario, I have multiple images/frames for each SpriteNode for the animation.
Please advice on an approach or point me in the right direction. Thanks.
Based on additional info from comments above:
With only 16 shapes, from the 16 frames, one of the more efficient ways would be to draw primitive shapes that roughly approximate the outlines of your character at each frame, and convert these to CGPaths. These can then be swapped in and out for each frame or (better) plucked out appropriately when there's a touch for testing based on the frame currently being shown at time of touch.
CGPaths are very lightweight structs, so there shouldn't be any performance problems with either approach.
CGPathContainsPoint is the old name of this test, which is now a modernised API for Swift 3 and onwards:
Troubles using CGPathContainsPoint SWIFT
There is an app called PaintCode, that's about $100 USD, which translates vectors into CGPaths, amongst other things, so you could use this to import your shapes. You can copy/paste vectors into it, which I suggest, because you might want to draw in a friendly drawing program. PaintCode doesn't have the world's best drawing experience.
Additionally, here's a free, online tool for doing the creation of a polygon path from textures. Probably more painful than using a drawing app and PaintCode, but it's FREE!
Alternative: Physics Bodies from Texture, and Contact with Touch
You can automagically create physics body shapes from a texture, like so, from the docs on this page:
let texturedSpaceShip = SKSpriteNode(texture: spaceShipTexture)
texturedSpaceShip.physicsBody = SKPhysicsBody(texture: spaceShipTexture,
size: CGSize(width: circularSpaceShip.size.width,
height: circularSpaceShip.size.height))
There have been reports of problems with determining if a point is within a given physics body, so it might be better to create a small physics object, place it where the touch is, and then determine if its in contact with the physics body shape appropriate for the current frame of the current game entity.
Caveat:
There's no telling (nor way to control, that I know of) how complex the resultant CGPaths are for these automagically created physics shapes.
I personally would just check the pixel of the current texture to see if is transparent or not. You can do this to get the pixel data:
(Note this code is hypothetical to get you started, I will try to work out a real example later on for you if you can't figure it out.)
(Also note, if you scale sprites, you need to handle that with converting touch location to texture)
let image = sprite.texture.cgImage()
if let dataProvider = image.dataProvider, let data = dataProvider.data
{
let screenScale = UIScreen.main.scale //let's handle retina graphics (may need work)
//touchedLocation is the location on the sprite, if the anchor was bottom left (it may be top left, will have to verify)
//So if I touch the bottom left corner of the sprite, I should get (0,0)
let x = touchedLocation.x * screenScale
let y = touchedLocation.y * screenScale
let width = sprite.texture.size().width * screenScale
let bpp = 4 // 4 bytes per pixel
let alphaChannel = 3 //Alpha channel is usually the highest byte
let index = bpp * (y * width + x) + alphaChannel
let byte = data.withUnsafeBytes({[UInt8](UnsafeBufferPointer(start:$0 + index,count:1))})
print(Alpha: \(byte))
}
else
{
//we have no data
}

Scene Kit: How to make SCNNode only rotate horizontally in Swift 2.0

I managed to create a tree and the program is supposed to only allow users to rotate this tree horizontally.
After looking at the doc, I use the following code
treeNode.physicsBody?.angularVelocityFactor = SCNVector3Make(0, 0, 1.0)
But this didn't do anything, I was still able to rotate the tree in every direction.
What is the correct way to limit node rotation in only horizontal direction?
Are you really trying to restrict the node's rotation? Or do you want to restrict the camera's rotation?
If the former, you'll have to provide much more detail on your body's physics and structure. An approach using SCNPhysicsHingeJoint seems like it would work.
let joint = SCNPhysicsHingeJoint.init(body: treeNode,
axis: SCNVector3Make(0, 0, 1.0),
anchor: SCNVector3Make(xpos, ypos, zpos))
If you're just trying to control the camera, though, you should turn off allowsCameraControl for the SCNView. That's only useful for quick and dirty testing. Then you can implement the technique described here (Rotate SCNCamera node looking at an object around an imaginary sphere) and modified here (SCNCamera limit arcball rotation).

How to make a sprite have gravity?

xcode 5 iOS7 sprite kit.
My wish is to make a sprite that has its own gravity.
Like a planet. If another sprite comes within a certain range of it, it will slowly pull the other sprite closer.
I have two sprites. One moving and one stationary. When the moving sprite gets in a given distance of the stationary sprite the stationary sprite gravity should slowly pull the other sprite towards it. This way the moving sprite would change its path in a soft curve.
My idea would be to calculate the distance from the stationary object to any other object and if close enough start pulling and if the moving object gets out of range ageing, then stop pulling.
Would probably need to research some vector calculation.
Thats my immediate thoughts.
Is this possible and how? Does it already exist?
A friend of mine did this for his physics dissertation. multibody gravity simulation. So yeah you can but you need to be willing to learn some maths. Apparently there is a clever optimisation to make it run decently nlog(n) rather than n^2). you probably want to ask this on the physics version of stack overflow to get a good answer. I have the code at home ... will post it later but you will want an explanation - i used it in an xna app. Its badass once you get it working - although if you want naturally orbiting objects then you will want to code them using parametric equations for easy and cool orbits. Simply because its hard to solve and with time even using double will result in some errors (the good implementations also work out the error and adjust - again will post later). But the real problem is solving for stable orbits. You then use the algorithm for free moving bodies such and player objects / npcs. Although solving accurate movement for npc in a changing field is v hard.
you want to look at this question: Jon Purdys answer is the one you want
multi body physics - gravity
and this one (which is linked from above) ...
https://gamedev.stackexchange.com/a/19404
There is not a dead-simple way of doing that in any platform as far as I know maybe except for some game engines/platforms that export for different platforms (cocos2d, construct 2 etc).
What you need is a physics engine whether you write one (which is a complicated but fun thing to do) or use an available one.
Luckily I've found a link describing the usage of the famous 2D physics engine "Box2D" on iOS.
This one explains how you can include Box2D in an openGL application (but you can apply this to other environments (sprite kit) I think altough I'm not an iOS guy);
http://www.iforce2d.net/b2dtut/setup-ios
Anyways, you now know what to look for...
For iOS 8.0+ : you have SKFieldNode : radialGravityField()
For iOS 8.0- : one solution could be : 3 to 9
add your sprite ( planet ) with its physics
add an invisible SKNode ( the gravity zone ) with its own physics, as a child of your sprite, but with a radius much more than your sprite's one
you have a little explanation about invisible node here : https://developer.apple.com/documentation/spritekit/skphysicsworld
both, your sprite and the invisible node are centered in a zero gravity world
we look for contact and not collision ( set correctly your bit masks )
when any object get in contact with the invisible node ( gravity zone ), first you remove any moving action or impulse from it and then we add to this object an SKAction to move it toward the center of your sprite ( planet )
at second contact between this object and your sprite ( planet ), you remove all actions again from the object with a velocity = zero