How to make SKEmitter particles stay relative to the background when I move my SKEmitterNode around the screen? - ios

I feel like this should be a very simple question, but I looked around and it seems to just be working for everybody automatically. But for some reason, when I move the particle emitter around the screen, the particles move with it, and there is no trail behind the emitter node of particles.
I am making a SpriteKit game of a character running around on the bottom of the screen, and he has a boost ability which releases small bubble particles behind him when he boosts because he is underwater. But the particles aren't staying relative to the screen, they are relative to the player and move with him.
Here's some code to add the boost bubbles:
func addBoostBubbles(){
boostBubbles = SKEmitterNode(fileNamed: "bubbleBoost")!
boostBubbles.particlePositionRange = CGVector(dx: player.frame.size.width, dy: player.frame.size.height)
boostBubbles.position = player.position
boostBubbles.zPosition = 0
self.addChild(boostBubbles)
}
I call this func to create the emitter node and set it to the player's position.
then to move the position of the bubbles in the didSimulatePhysics func I have this:
boostBubbles.position.x += xAcceleration
I see the bubbles on the screen and the emitter node is moving to the right places, but I want them relative to the background so the bubbles just slowly float up behind the player.
Any help would be greatly appreciated!!!!

Set the targetNode property of your emitter to be the background node. In addBoostBubbles, try adding the line:
boostBubbles.targetNode = <background node name>
https://developer.apple.com/documentation/spritekit/skemitternode
targetNode - The target node that renders the emitter’s particles.
This causes the particles to render as though they are children of the background.
If you don't have a background node then you'll need to add one.

Related

SpriteKit physics: How to make a player sprite follow the (sloped) ground

I am creating a tilemap platform game in SpriteKit. I assigned collision paths to the physics body of all ground tiles and made them non-dynamic. To the player I assigned two collision polygons: a circle on the bottom and a rectangle on the top.
The player sprite has a fixed position on screen, while the level is scrolling from right to left. Now, as long as the player sprite is on flat ground, the collisions work perfectly and the player is walking on the ground. However, I also have some sloped terrain tiles that I want the player to follow (e.g. walking uphill). But when the player reaches a sloped tile, he simply bounces off of it, being unable to "climb" it.
Similarly, when I drop the player from above on a sloped tile, he slides down the "hill", instead of remaining in position.
I have both restitution and friction set to 0.
So how can I make the player sprite follow the ground regardless of its shape and how can I make the player stay on a sloped tile instead of sliding down?
I tried using SKConstraints with positionX set to a constant value. At first it seemed to work, but then the player got stuck in the middle of a sloped tile and eventually fell through it.
I also tried different shapes of collision polygons on the player (e.g. a rectangle instead of a circle at the bottom) but that changed nothing.
Any help is appreciated!
This has more to do with your game logic instead of your map properties. You need to have several "states" for your player. For example, if your player is idle you can set the CGVector to 0,0. This will stop the player from moving in any direction.
To give you some examples on movement. Let's say you want to make your object move right:
// move node's physics body to the right while leaving vertical movement as is
// 160 is just an example
myNode.physicsBody.velocity = CGVectorMake(160, self.physicsBody.velocity.dy);
// do not allow right movement to exceed 160
if(myNode.physicsBody.velocity.dx > 160)
myNode.physicsBody.velocity = CGVectorMake(160, self.physicsBody.velocity.dy);
To move left you inverse the dx value:
myNode.physicsBody.velocity = CGVectorMake(-160, self.physicsBody.velocity.dy);
if(myNode.physicsBody.velocity.dx < -160)
myNode.physicsBody.velocity = CGVectorMake(-160, self.physicsBody.velocity.dy);
Allow myNode to be affected by gravity and it should remain in contact with the ground as it moves down a slope.
It's a tilemap platform game...
Then gravity isn't important, put gravity to a very low value and then change all your impulses for the jumps and such in relation to the change in gravity...
OR,
Possibly, if the game isn't randomly generated you can set up a uibezierpath, and turn the path off if he stops moving up the hill.
But then if he stopped mid-hill or was starting from the top, he would still slide down...
And increasing friction (not setting it to 0) may help. Try friction at 1?

How does one initialize/move a camera in a SpriteKit program using Swift?

I have a map and it's bigger than the device's screen size, so I want the user to be able to navigate around the map by dragging the screen, similar to Clash of Clans.
How can I create a camera view so I can drag the camera around the map?
Also, how can I customize where the camera's center begins as the scene switches to the map?
theres no camera in swift. the idea is you add your background to a "world node"
// set up stuff you want to add to world node
let bg = SKSpriteNode(... initializer
// make a "worldNode" that you move around
self.worldNode = SKNode()
// add your bg to the worldNode
worldNode.addChild(bg)
// add worldNode to the scene
self.addChild(worldNode)
ok so now you have that.. now you make some method to move the world around depending on a position
func centerViewOn(centerOn: CGPoint) {
self.worldNode.position = CGPoint(x: -x, y: -y)
}
You pass in the players position, and the worldNode will move. That's the general idea.
You probably need to add some conditional stuff in here so that the camera doesn't move too far. With this code, the camera has no limit, and can look past the edge of your game world. You'd want to limit it so it stops following the player when they reach the edge.

SKEmitterNode emitting particles before physics are simulated

I have an SKEmitterNode centered on my player to leave a trail of particles. My player has a physics body and it's moved by physics, not by manually updating it's position.
The issue I'm having is that when the speed of my player increases the particles are emitted from a point behind the player.
I discovered that this is happening because the particles are emitted in the "evaluate actions" part of the frame cycle. My player is afterwards moved by the "simulate physics" part.
The solution I found as a workaround is to move the SKEmitterNode (in the update callback) to the point where my player will be after the physics calculations. This is the code I used:
particleEmitter.position = CGPointMake(
player.position.x + player.physicsBody!.velocity.dx * dt,
player.position.y + player.physicsBody!.velocity.dy * dt
)
UPDATE
At first I had my emitter as a child node of the player, then is when I observed the problem.
I also tried to sync the emitter position exactly to the player position, without accounting for distance moved since the last update (velocity * dt), same problem.
My question is, what would be the correct way of solving this?
UPDATE 2
I've created a playground demonstrating the issue. Here I have the emitter as a child of the player. The more you increase the player's velocity the bigger the gap between the player and the emitted particles.
https://github.com/ovidiupruteanu/SKEmitterNodeTest-Playground
Here is the frame cycle from the apple docs
Your code only estimates the next position of the player. It doesn't consider other factors that may affect the player's position, such as collisions, force fields, linear damping, etc. I suggest you set the emitter's position to the player's position in the didSimulatePhysics callback or add the emitter as a child of player.
Rather than manually repositioning the emitter on every frame, let SpriteKit do that work for you: make the emitter a child node of the player sprite, and the emitter point will stay at the same location relative to the player whenever the player moves.
If you go this route, you might have a problem with the emitted particles also following the player in ways you don't want. You can resolve this by setting the emitter's targetNode to the node containing the player.

How to locate CCParticleFire, so that it will be always at the same position as a moving sprite?

I have a sprite and a particle fire. Sprite is moving, so I want fire be at the same place as sprite all the time.
That's what I tried. _abcdis the name of sprite.
CCParticleFire *emitter;
emitter = [CCParticleSystem particleWithFile:#"suchfire.particle"];
emitter.position=ccp(_abcd.position.x,_abcd.position.y);
[self addChild: emitter z:10];
When I run the game, fire is located in the lower left corner. Any ideas?
Your sprite is moving after its position is assigned to the emitter. Remember that the position you're assigning to your emitter is not going to update with the movement of the sprite.
So the best way forward is to update the emitter's position as the position for the sprite updates. This can be done in your update method.
Or better yet apply whatever movement you're apply to your sprite, be it by the game or the user, to your emitter.

Emitter not rotating with parent node

Code --> http://pastebin.com/W3DMYjXa
I am tinkering with SpriteKit and I cannot seem to get an emitter node to rotate with my spaceship the way I would like.
I watched the Apple Tech Talks Session where they described making a spaceship and using an emitter for the thrust exhaust, but they lock the ship to only face one direction.
In my experiment I am trying to allow the player sprite (spaceship) to travel in any direction, I have rotation and scrolling working for the player, but the particle emitter doesn't seem to rotate with the player.
my hierarchy looks something like this
Scene
-->World Node
-->Player Node
---->Player Sprite
---->Emitter Node
My theory is that If I rotate (Player Node) it should rotate both of its children, and it does rotate them, but the emitter continues to emit in the same direction.
I can change the emission angle manually, but it seems needlessly complicated.
here is what I am using to rotate
-(void)rotatePlayerToDirection:(TTDirection)direction {
CGFloat radDir;
CGFloat emiDir;
scrollDirection = direction;
switch (direction) {
case TTUp:
radDir = 0;
emiDir = 3.142;
break;
case TTRight:
radDir = 4.712;
emiDir = 1.571;
break;
case TTDown:
radDir = 3.142;
emiDir = 0;
break;
case TTLeft:
radDir = 1.571;
emiDir = 4.712;
break;
default:
break;
}
SKAction *rotatePlayer = [SKAction rotateToAngle:radDir duration:0.1 shortestUnitArc:YES];
[playerNode runAction:rotatePlayer];
}
Am I missing something here?
Here is a video of this in action
http://youtu.be/NGZdlB9-X_o
I'm fairly certain there is a bug in spritekit to do with the targetNode and rotation. The other answer seems to suggest this is expected behavior, but that ignores that the docs explicitly give this situation as a motivation for the existence of targetNode.
Working with Other Node Types
What you really want is for the particles to be spawned, but thereafter be
independent of the emitter node. When the emitter node is
rotated, new particles get the new orientation, and old
particles maintain their old orientation.
It then gives an example using targetEmitter on how to achieve this. However, the example code does not work.
It seems that setting targetNode breaks particle rotation.
UPDATE: I found a workaround.
Spritekit is failing to adjust the SKEmitterNode.emissionAngle property when SKEmitterNode.targetNode is set. You can work around this by setting it manually after actions have been processed.
Assuming that your SKEmitterNode has only one parent, you can do something like this in your scene.
- (void)didEvaluateActions
{
// A spaceship with a thrust emitter as child node.
SKEmitterNode *thrust = (SKEmitterNode *)[self.spaceship childNodeWithName:#"thrust"];
thrust.emissionAngle = self.spaceship.zRotation + STARTING_ANGLE;
}
Note that if there are multiple ancestor nodes which may be rotated, you will need to loop through them and add all of their zRotations together.
I know this is an old question, and the OP has probably found a solution or workaround, but I thought I would add by two pence worth, in case it helps anybody else.
I am just starting out with SpriteKit and Swift, and am developing a game where nodes fly around and collide with each other, changing direction of travel frequently.
I add an emitter to each node, and initially found that as the node rotated and changed direction, the emission 'trail' remained fixed. I then read that the emitter should have its target node set not as the node it is a child of, but the scene they both exist in.
That at least made the particle trail twist and turn realistically rather than just spurt out in one direction.
But the nodes can spin and changes direction, and I wanted the particles to trail away from the node in the opposite direction to its travel - just like a smoke trail from a plane or rocket.
As the node may rotate, setting the emitters angle of emission to the z-rotation of the node does not work. So...
I track all onscreen nodes in a dictionary, removing them from the scene as they travel off the screen.
So in didSimulatePhysics I use the same dictionary to get the node and calculate the angle of travel from the velocity vector, and then set the emitters emission angle accordingly :
import Darwin
// in your scene class...
override func didSimulatePhysics() {
removeOffScreenParticles()
for (key,particle) in particles {
let v = particle.physicsBody!.velocity
particle.trail!.emissionAngle = atan2(v.dy, v.dx) - CGFloat(M_PI)
}
}
I am aware that this calculation and adjustment is being performed for each on screen node, in every frame, so will probably use my frame counter to only do this check every n'th frame if performance becomes an issue.
I hope this helps someone!
You are setting the emitter's targetNode property to the background. Note that this forces the emitter's particles to be rendered by the background node, and they will be treated as if the background was their parent. So, the particles aren't changing the angle, because the rotation of the background does not change.
Remove [emitter setTargetNode:backgroundNode] and the emitter's emission angle should be rotating correctly along with the player.
If you're looking for a 'middle ground', where the angle rotates along with the player, while the already-rendered particles aren't 'stuck' to the emitter, try this:
First, do not set the targetNode on the emitter (it defaults to nil).
Second, just as you are about to run the rotation action, temporarily set the targetNode to another node, and reset it back to nil when it completes (so that the particles can rotate along):
emitter.targetNode = backgroundNode;
[playerNode runAction:rotatePlayer completion:^{
emitter.targetNode = nil;
}];
Note that the results are also 'middle ground' - the emitter 'puffs' as the target node changes (the previous particles are removed, and new ones are rendered by the new target node). Hope that helps.
Other than that, there's no really straightforward way of achieving this - setting the emission angle manually might be the simplest way, after all. Here's one way to do it, right before running the rotation (the emitter target node is still nil, also, there's no need to hardcode emission angles):
float originalAngle = emitter.emissionAngle;
emitter.emissionAngle = emitter.emissionAngle - radDir;
[playerNode runAction:rotatePlayer completion:^{
emitter.emissionAngle = originalAngle;
}];

Resources