How to reduce the impact of gravity on a single SKSpriteNode - ios

I am building an endless runner game where platforms appear at random intervals and then scroll right to left across the screen.
I have a sprite that jumps up vertically using
- (void)makeCharacterJump {
[self.spriteCaveman.physicsBody applyImpulse:CGVectorMake(0.0f, 80.0f)];
}
The problem is that the effect of gravity on the sprite means that it falls quite quickly and cant make the gap between the platforms.
What I would like to do is slightly slow down the effect of gravity on the falling sprite so it creates the impression of slightly floating down.
Any ideas?

If the character is the only node affected by gravity then you can change the scene’s gravity with:
self.physicsWorld.gravity = CGVectorMake(0, desiredGravity);
If it is not then you’ll have to play with the character’s physics body properties: friction, linearDamping or angularDamping values.
Hope that helps.

Related

Bouncing Ball SKPhysicsBody - Stop Bouncing Perpendicular Forever

So I'm making a brick break style game using "Ray Wenderlich's amazing tutorial" in Spritekit/Swift, just like the tutorial.
I successfully have a ball bouncing around the screen using a SKSpriteNode() and SKPhysicsBody() and I've been tweaking values for the impulses used to begin the ball bouncing around the screen forever.
However, I stumbled upon a problem which I hope to find a solution.
Sometimes, in my game, the Sprite will bounce around and become "Wall Locked" bouncing almost Perpendicular (or straight) between two walls, (give or take a few pixels)! So ends up Zig-Zagging across the whole screen between two said walls for ages.
What I want to do is, should this happen and the ball get "Wall Locked" to introduce a new impulse to get it moving again...
How can this be done? For example, if it has bounced between the top and bottom walls 10 times, then it's time to adjust it's angle/introduce a new impulse.
Could the last 10 positions be stored in an array, then test if their almost perpendicular somehow?
If you inspect the velocity property of your Sprite, you could detect when either of its values is close to zero and then make them something that is not so close to zero. This would stop it getting stuck moving just horizontally or vertically.

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?

Make a SCNNode drop using gravity?

I have a SceneKit setup and have one Sphere in it that is setup as a Dynamic body.
I am able to run the app and see the sphere drop on the static body floor.
What I am trying to do is setup the scene so the sfere initially does not drop.
Then when a function is run I want the sfere to drop.
what is the correct logic / steps to make the scene suddenly (maybe when a button is pressed or something) drop the sphere?
I have tried also to set the sphere to mass 0 and then set the mass to 100 but it does not cause the drop...
Mass doesn't control how fast something falls. This is true in the real world, but more so in simulations that take shortcuts instead of simulating every detail of real-world physics. (Sadly, iOS devices still don't have the CPU power to account for the rotating reference frame of the Earth, the Van der Waals attraction between your sphere and any body especially close to it, the strong force that keeps its triangles atoms together, etc etc.) In SceneKit, gravity is just a constant acceleration in a specific direction.
Setting mass to zero and switching it to something else interferes with the distinction between static/kinematic and dynamic bodies... so don't do that.
As #mnuages notes, you can add/remove the physics body from your sphere when you want it to be affected or unaffected by physics entirely.
But what if you want to keep the sphere's physics body for other reasons—such as allowing other bodies to collide with it even before you make it start falling? There are a few approaches you could use for that:
Set the sphere body's damping to 1.0.
Set the sphere body's velocityFactor to zero (at least in the direction of gravity).
Both of those will keep the sphere from moving when something else hits it. If you want the ball to get knocked around, but not be affected by gravity, the best thing to do might be to switch out scene gravity for physics fields:
Set scene.physicsWorld.gravity to SCNVector3Zero.
Add a SCNPhysicsField created with the linearGravityField constructor to your scene, and set its direction and strength to get the kind of gravity behavior you want.
Set the categoryBitMasks on both your sphere body and the gravity field such that the field affects other bodies but not the sphere.
Whichever of these methods you use, you can change them when you want to "turn gravity on" for the sphere: reduce the damping, reset the velocityFactor, or change the sphere's or the gravity field's categoryBitMask.
As of iOS 9, you can set the isAffectedByGravity property to false then flip the value to true to make the sphere drop: https://developer.apple.com/reference/scenekit/scnphysicsbody/1514738-isaffectedbygravity
setting a physics body to sphere only when you want to it to be affected by gravity should work.

SpriteKit - Making a sprite defy gravity (like a balloon)

Does anyone have any idea how I can make my SKSpriteNode defy gravity? I thought of inverting the default gravity but realise I also need things to fall too!
It seems like it should be easy but reading through the documentation I can’t see how I would do it!
Thanks
Update: In iOS 8 / OS X Yosemite (10.10), physics fields provide an elegant solution to these sorts of problems. Here's a quick take on using them to add buoyancy (for a specific set of nodes) to your scene.
Create an SKFieldNode with the linearGravityFieldWithVector constructor, providing a vector that's the opposite of gravity, and add the field node to your scene.
Set the fieldBitMask on your balloons to something unique.
Set the categoryBitMask on the field to something that overlaps with the balloons' fieldBitMask, but that does not overlap with the fieldBitMask of any other bodies.
Now, the balloons will rise or hold steady, but other objects will fall. Tweaking the field's strength will let you tune whether the balloons' buoyancy is perfectly balancing gravity (so that they float in place, but are disturbed when touched), or slightly more or less than gravity (so that they slowly rise or fall).
By default, a field is infinite, covering the whole scene, but you can change that with the field's region property to limit it to a portion of the scene. (This is useful if you want to simulate buoyancy in water — once an object rises past the top of the field at the water's surface, it falls back in.)
Also, if you want variable buoyancy as per #TheisEgeberg's answer, you can control its variation over distance with the falloff property.
In iOS 7 / OS X Mavericks (10.9), or if you want more precise control over which forces apply where and when, you can use the approach from my original answer below.
If you want an object to really float like a balloon — that is, to be buoyant, affected by gravity but also counteracting it — you'll need to apply a force to it on every frame (i.e. in your update: method).
Beware scaling: gravity is a constant acceleration, but if you're applying a force to counteract gravity, a force is proportional to mass. To make a vector that perfectly balances gravity for use in applyForce:, you'll need to:
scale the gravity vector by {-1,-1,-1} to point in the opposite direction
scale by the mass of the body you're applying the force to (F = ma, where gravity or anti-gravity is a).
scale by 150 — there's a bug where the SKPhysicsWorld.gravity property isn't in the same units as applyForce:. (If you turn SKPhysicsWorld gravity off and use SKFieldNode gravity instead, you don't need to do this.)
Unlike turning off affectedByGravity and applying an action to make the balloon rise, this approach works well with the rest of the physics sim. With a balancing force exactly equal to gravity, the balloon will float in place — after colliding with other things it'll return to equilibrium. If the balancing force is greater than gravity, the balloon will rise, but its rise will be hindered by other bodies in its way.
First off, an SKSpriteNode isn't affected by gravity at all. It is the SKPhysicsBody that belongs to the node that is affected by gravity.
Second...
myNode.physicsBody.afectedByGravity = NO;
:D
If you want it to rise upwards then you can add an action to it...
SKAction *moveAction = [SKAction moveByX:0 y:-10 duration:1];
SKAction *repeatingAction = [SKAction repeatActionForever:moveAction];
[myNode runAction:repeatingAction];
As many have said it's about counterforce.
So yes, you can apply a counterforce to the balloon to make it go upwards.
But to make it look like a balloon you need to understand what makes a balloon go up: Air pressure. Since the helium or whatever light gas you are using is lighter than air it will start to go up, or in other words the heavier air will go under the balloon. It's like a piece of wood in water, the heavier water will go under the wood, till the wood is soaked and gets even heavier than the water.
So what you should do is to make the counterforce adapt to the height of the balloon, the higher it gets the less pressure you apply upwards. This is a way to simulate buoyancy.
Here’s my answer:
- (MyClass *)newRisingObject
{
MyClass *risingObject = [MyClass spriteNodeWithImageNamed:#"image"];
[risingObject setPosition:CGPointMake(CGRectGetMidX(self.frame), CGRectGetMinY(self.frame))];
[risingObject setName:#"name"];
[risingObject setUserInteractionEnabled:YES];
// Physics
//
[risingObject setPhysicsBody:[SKPhysicsBody bodyWithCircleOfRadius:risingObject.size.width / 2.0f]];
[risingObject.physicsBody setRestitution:1.0f];
[risingObject.physicsBody setFriction:0.0f];
[risingObject.physicsBody setLinearDamping:0.0f];
[risingObject.physicsBody setAngularDamping:0.0f];
[risingObject.physicsBody setMass:1.3e-6f];
return risingObject;
}
.
- (void)didMoveToView:(SKView *)view
{
/* Setup your scene here */
MyClass *risingObject = [self newRisingObject];
[self addChild:risingObject];
}
.
- (void)update:(CFTimeInterval)currentTime
{
/* Called before each frame is rendered */
[self enumerateChildNodesWithName:#"name"
usingBlock:^(SKNode *node, BOOL *stop)
{
// Push object up
//
[node.physicsBody applyImpulse:CGVectorMake(0.0f, node.physicsBody.mass * OBJECT_ACCELERATION)];
}];
}

Sprite Kit physics on word rotation - collision and gravity Sprite-kit

I'm working on a new project and I am completely stuck with the main character movements.
The picture at this link explain my situation
http://www.chr.to/stuck.jpg
I have a world (black) a character (red) and an obstacle
The character and the world are children of SELF
The obstacle is a world's child
My goal is to move the character around the world but it must be in the same position all the time, just the world must turn below its feet.
To achieve this, I rotate the world in the opposite direction of the character direction and the effect is perfect (I get direction from a joystick)
-(void)update:(CFTimeInterval)currentTime {
rotation = rotation + input;
wordTest.zRotation = rotation; }
The biggest problem is when I found an object in the world.
The character and all obstacles are physics objects.
When the character hit an obstacle it drags off the world because the rotation continues and It can't keep its position in the middle of the screen .
Probably it's not the best approach, I have to find the way to stop the rotation...
or Do you have a better suggestion?
thank you guys
Set up a BOOL flag called canRotate, and use it to check whether rotation must be applied in the -update method.
-(void)update:(CFTimeInterval)currentTime
{
if (canRotate)
{
rotation = rotation + input;
wordTest.zRotation = rotation;
}
}
Set this flag as YES in the -init method and, when a contact between the character and obstacle is triggered in -didBeginContact, set the flag to NO.

Resources