I'm familiar with swift but I've started dabbling my hand in spritekit. I've been following a tutorial about created an endless runner. The approach taken by the author is to create a single SKNode that contains all the children. This container node is then moved rather than moving all the child Nodes individually. But what's got me stumped is that the container node doesn't have a size associated with it so I'm a bit confused as to how/why this works and the author doesn't really explain it.
So we have
let containerNode = SKNode()
let thePlayer = Player("image":"player") //SKSpriteNode
let inc = 0
override func didMoveToView(){
self.anchorPoint = CGPointMake(0.5,0)
addChild(containerNode )
containerNode.addChild(player)
moveWorld()
}
func moveWorld(){
let moveWorldAction = SKAction.moveByX(-screenWidth, y:0, duration:6)
let block = SKAction.runBlock(movedWorld)
let seq = SKAction.sequence([moveWorldAction,block])
let repeatAction = SKAction.repeatActionForever(seq)
containerNode.runAction(repeatAction)
}
func movedWorld() {
inc = inc + 1
addObjects()
}
func addObjects() {
let obj = Object()
containerNode.addChild(obj)
let ranX = arc4random_uniform(screenWidth)
let ranY = arc4random_uniform(screenHeight)
obj.position = CGPointMake(screenWidth * (inc + 1) + ranX, ranY)
}
There's some conversion that I've omitted in the code above from int to float but it's not necessary for the point I want to understand.
I get why when new objects are created we do the multiple by the increment, but what I don't get is the containerNode doesn't have a size, so why do it's children show? Is this the most efficient way to do this?
I'm assuming that it's just convenience rather than moving all the other objects individually but the fact that it doesn't have a size is confusing me.
Since an SKNode isn't rendered, it doesn't need (or have) a size property. Only SKNode subclasses (SKLabelNode, SKShapeNode, etc.) that are visible require a size (declared explicitly or calculated implicitly). For example, SpriteKit needs to know the size of an SKSpriteNode with a 20 x 20 texture to correctly render it. You can use SKNode's calculateAccumulatedFrame method to determine the total size (a rectangle) of all of the descendants (other than other SKNodes) in its node tree.
If I understand the documentation for SKNode correctly this little section should answer your question:
Every node in a node tree provides a coordinate system to its
children. After a child is added to the node tree, it is positioned
inside its parent’s coordinate system by setting its position
properties. A node’s coordinate system can be scaled and rotated by
changing its xScale, yScale, and zRotation properties. When a node’s
coordinate system is scaled or rotated, this transformation is applied
both to the node’s own content and to that of its descendants.
Source
Again, if I'm reading this correctly, it seems that when a node is added to a node tree it inherits it's parent coordinate system. So by default containerNode is the same size as self in this case.
Also according to the frame property of a SKNode:
The frame is the smallest rectangle that contains the node’s content,
taking into account the node’s xScale, yScale, and zRotation
properties. Source
Which again sounds like if a frame isn't set it takes the smallest rectangle (self in this case or it might be understood that it's the children of containerNode I'm not sure) as it's own frame.
Whatever the case is, it's inheriting it from another SKNode.
Related
What I'm looking for is a method SCNNode.convertOrientation(_:to), which would work similarly to SCNNode.convertPosition(_:to) or SCNNode.convertTransform(_:to), only for a rotation/orientation.
I first tried
node.simdOrientation = from.simdWorldOrientation / to.simdWorldOrientation * orientation
but that doesn't seem to work. The only way I could make it work was by using a temporary node on which to do the whole transform conversion, which seems unnecessarily inefficient. (In the code below I'm also converting the node's position, which I put there just to visually check that the whole conversion was successful.)
node.position = to.convertPosition(node.position, from: from)
let temp = SCNNode()
temp.setWorldTransform(node.worldTransform)
temp.transform = temp.convertTransform(SCNMatrix4Identity, to: to)
node.simdOrientation = temp.simdOrientation
node.removeFromParentNode()
to.addChildNode(node)
Is there a particular reason why there is no built-in method for doing this? Am I not supposed to do this at all?
I have a (moving) sprite node.
I'd like to detect other (moving) sprite nodes within a certain range of this node. Once one is detected, it should execute an action.
The playing an action part is no problem for me but I can't seem to figure out the within-range detection. Does have any ideas how to go about this?
A simple, but effective way to do this is comparing the position's in your scene's didEvaluateActions method. didEvaluateActions gets called once a frame (after actions have been evaluated but before physics simulation calculations are run). Any new actions you trigger will start evaluating on the next frame.
Since calculating the true distance requires a square root operation (this can be costly), we can write our own squaredDistance and skip that step. As long as our range/radius of detect is also squared, our comparisons will work out as expected. This example shows detect with a "true range" of 25.
// calculated the squared distance to avoid costly sqrt operation
func squaredDistance(p1: CGPoint, p2: CGPoint) -> CGFloat {
return pow(p2.x - p1.x, 2) + pow(p2.x - p1.x, 2)
}
// override the didEvaluateActions function of your scene
public override func didEvaluateActions() {
// assumes main node is called nodeToTest and
// all the nodes to check are in the array nodesToDetect
let squaredRadius: CGFloat = 25 * 25
for node in nodesToDetect {
if squareDistance(nodeToTest.position, p2: node.position) < squaredRadius {
// trigger action
}
}
}
If the action should only trigger once, you'll need to break out of the loop after the first detection and add some sort of check so it does not get triggered again on the next update without the proper cool down period. You may also need to convert the positions to the correct coordinate system.
Also, take a look at the documentation for SKScene. Depending on your setup, didEvaluateActions might not be the best choice for you. For example, if your game also relies on physics to move your nodes, it might be best to move this logic to didFinishUpdate (final callback before scene is rendered, called after all actions, physics simulations and constraints are applied for the frame).
Easiest way I can think of without killing performance is to add a child SKNode with an SKPhysicsBody for the range you want to hit, and use this new nodes contactBitMask to determine if they are in the range.
Something like this (pseudo code):
//Somewhere inside of setup of node
let node = SKNode()
node.physicsBody = SKPhysicsBody(circleOfRadius: 100)
node.categoryBitMask = DistanceCategory
node.contactBitMask = EnemyCategory
sprite.addNode(node)
//GameScene
func didBeginContact(...)
{
if body1 contactacted body2
{
do something with body1.node.parent
//we want parent because the contact is going to test the bigger node
}
}
In my program I have a method called addObstacle, which creates a rectangular SKShapeNode with an SKPhysicsBody, and a leftward velocity.
func addObstacle(bottom: CGFloat, top: CGFloat, width: CGFloat){
let obstacleRect = CGRectMake(self.size.width + 100, bottom, width, (top - bottom))
let obstacle = SKShapeNode(rect: obstacleRect)
obstacle.name = "obstacleNode"
obstacle.fillColor = UIColor.grayColor()
obstacle.physicsBody = SKPhysicsBody(edgeLoopFromPath: obstacle.path!)
obstacle.physicsBody?.dynamic = false
obstacle.physicsBody?.affectedByGravity = false
obstacle.physicsBody?.contactTestBitMask = PhysicsCatagory.Ball
obstacle.physicsBody?.categoryBitMask = PhysicsCatagory.Obstacle
obstacle.physicsBody?.usesPreciseCollisionDetection = true
self.addChild(obstacle)
obstacle.runAction(SKAction.moveBy(obstacleVector, duration: obstacleSpeed))
}
In a separate method, called endGame, I want to fade out all the obstacles currently in existence on the screen. All the obstacle objects are private, which makes accessing their properties difficult. If there is only one on the screen, I can usually access it by its name. However, when I say childNodeWithName("obstacleNode")?.runAction(SKAction.fadeAlphaBy(-1.0, duration: 1.0)), only one of the "obstacles" fades away; the rest remain completely opaque. Is there a good way of doing this? Thanks in advance (:
You could probably go with:
self.enumerateChildNodesWithName("obstacleNode", usingBlock: {
node, stop in
//do your stuff
})
More about this method can be found here.
In this example I assumed that you've added obstacles to the scene. If not, then instead of scene, run this method on obstacle's parent node.
And one side note...SKShapeNode is not performant solution in many cases because it requires at least one draw pass to be rendered by the scene (it can't be drawn in batches like SKSpriteNode). If using a SKShapeNode is not "a must" in your app, and you can switch them with SKSpriteNode, I would warmly suggest you to do that because of performance.
SpriteKit can render hundreds of nodes in a single draw pass if you are using same atlas and same blending mode for all sprites. This is not the case with SKShapeNodes. More about this here. Search SO about this topic, there are some useful posts about all this.
I have a node that have a constraint; to be more specific, it has an SCNLookAtConstraint :
let constraint = SCNLookAtConstraint(target: scene.retriveNodeFromScene(cameraNodeName))
constraint.gimbalLockEnabled = false
self.constraints = [constraint]
But when I want to move node to other coordinates it just doesn't move. I don't receive any error, just nothing happens. I have made some tests, and if I remove constraint, everything is ok, node moves with no problem. So, what should I do? Is there any solution for my problem or should I find another way, equivalent with my constraint, but also compatible with SCNAction?
code for action:
let timeForAction = calculateTimerForSecoundAction()
let action = SCNAction.moveTo(calculateEndingLocation(), duration: timeForAction)
let delay = dispatch_time(DISPATCH_TIME_NOW, Int64(NSEC_PER_SEC * timeForAction))
self.runAction(action)
explodeAfterReachingFinalPosition(timeForAction)
you could create a new intermediate node that you'll use for the action, and have your current node as a child node with the lookAt constraint.
Same issue as the original poster.
I solved it with MNAUGES suggestion.
The 'LookAt' constraint breaks/prevents the SCNActions from happening in the view. Interestingly, the camera node WAS moving - according to the console - just not updating in the view. I could also move the camera node in the view with a change to cameraNode.position = newPosition - but without the nice animated transition.
Parent your cameraNode to an emptyNode. Assign the lookAt constraint to the cameraNode and the moveTo SCNAction to the emptyNode.
In my game, I'm trying to determine what points to dole out depending on where an arrow hits a target. I've got the physics and collisions worked out and I've decided to draw several nested circular SKShapeNodes to represent the different rings of the target.
I'm just having issues working out the logic involved in checking if the contact point coordinates are in one of the circle nodes...
Is it even possible?
The easiest solution specific to Sprite Kit is to use the SKPhysicsWorld method bodyAtPoint:, assuming all of the SKShapeNode also have an appropriate SKPhysicsBody.
For example:
SKPhysicsBody* body = [self.scene.physicsWorld bodyAtPoint:CGPointMake(100, 200)];
if (body != nil)
{
// your cat content here ...
}
If there could be overlapping bodies at the same point you can enumerate them with enumerateBodiesAtPoint:usingBlock:
You can also compare the SKShapeNode's path with your CGPoint.
SKShapeNode node; // let there be your node
CGPoint point; // let there be your point
if (CGPathContainsPoint(node.path, NULL, point, NO)) {
// yepp, that point is inside of that shape
}