Accelerate an SKSpriteNode - ios

Is it possible to accelerate an SKSpriteNode?
I know the velocity can be set easily with node.physicsBody.velocity but how hard would it be to set it's acceleration?

Working backwards from newtons second law a motion : F = m.a
You can achieve a desired acceleration by using applyForce where the force is the acceleration multiplied by the mass.
[node.physicsBody applyForce:CGVectorMake(node.mass*acceleration.dx,
node.mass*acceleration.dy)];

applyImpulse instantly imparts a quantity of energy (in Newton.seconds). Your object doesn't accelerate so much as instantly reach the desired speed. This is unlikely to look very natural as it implies near-infinite power (energy divided by time) therefore is only really suitable for explosions (shooting bullets for example).
applyForce applies a force (in Newtons) for the time-interval the simulation runs in (i.e.: 1/60th of a second). This allows you to correctly accelerate an object and simulate many different forces being applied simultaneously (gravity, wind, rocket boost etc.) in different directions.
Also worthy of note is applyForce:atPoint: this allows you to specify at which point of the object the force is applied. For example if you were simulating a balloon with a string, the string would apply its weight to the bottom of the balloon, whereas the lift of the base in balloon would be applied to the centre of the ballon. Applying a force elsewhere than at the centre of gravity will cause the object to rotate.
Lastly, you have the corresponding applyAngularImpulse: and applyTorque: which allow you to influence an object's rotation speed. This is useful for example if you want to keep an object upright despite various bounces: you could apply a torque proportional to the angle (or square it if you want to avoid oscillations).
All this is very well documented here: SKPhysicsBody
But if you need more information about the physics themselves then have a look at Wikipedia:
Newtonian Physics and associated pages (angular momentum for example).

If you want it to accelerate, then you should change the direction of gravity for the object
self.physicsWorld.gravity = CGVectorMake(dx,dy)
but this would make everything accelerate, if that is okay

Related

SpriteKit - how do I apply a constant velocity and change on touch - swift

How do I make my player move left/right at a constant speed until the user touches the screen again, which will then make the player change direction right/left and run that way at a constant speed etc..
I have tried looking at other answers but can't figure out a working answer.
I've set linearDamping to 0 already.
There are two basic ways to apply velocity.
One is by applying forces to physics bodies, or giving them velocities.
Two is positional transformations, usually done with SKActions.
They're not compatible.
Since you're using physics, you need to either apply force or set a velocity.
I think you should probably take the time to read this entire page:
https://developer.apple.com/documentation/spritekit/skphysicsbody
Here's the setting velocity cherry from it:
First, you can control a physics body’s velocity directly, by setting
its velocity and angularVelocity properties. As with many other
properties, you often set these properties once when the physics body
is first created and then let the physics simulation adjust them as
necessary.
And here's the outline on forces:
You can apply a force to a body in one of three ways: A linear force
that only affects the body’s linear velocity. An angular force that
only affects the body’s angular velocity. A force applied to a point
on the body. The physics simulation calculates separate changes to the
body’s angular and linear velocity, based on the shape of the object
and the point where the force was applied.

How to get Constant Velocity for Spritekit Gravity

I am making a Tetris kind of game, where I want my blocks to fall at a constant velocity. I want to achieve it using SpriteKit Physics Words Gravity.
Problem is that gravity is necessarily acceleration and hence block start to move faster as they fall. I know I can turn gravity off and use actions to move the block but I wish to do it with gravity.
Is there a way to make the gravitational force in SpriteKit world a linear constant velocity?
Using the default physics you will not achieve what you are looking for.
In the definition of Gravity in Spite Kit is clear that is a acceleration, so is no possible to achieve linear speed with it.
A vector that specifies the gravitational acceleration applied to
physics bodies in the physics world.
But, you can have some workarounds to achieve the behavior you want.
Gravity Acceleration 0, and add speed to the falling object.
Limit the maximum Speed of an Object.
Do you own physics
I Think the best way to do it, with gravity working as default, is by limiting the maximum speed.
2 - Limit the maximum Speed
Consulting this post.
In didSimulatePhysics(), you can verify the speed of the object, and limit it.
Like this (Credits to #Andrew, in the original post)
- (void)didSimulatePhysics {
if (node.physicsBody.velocity.x < MAX_SPEED_X) {
node.physicsBody.velocity = CGVectorMake(MAX_SPEED_X, MAX_SPEED_Y);
}
}

A way to apply zRotation so that it affects the SKPhysicsBody accordingly?

Let's say I have a SKSpriteNode that represents a car wheel, with a circular SKPhysicsBody successfully attached to it. The genre would be sideways scrolling 2d car driving game/simulator, obviously.
What I want is to calculate all the in-motor physics myself without resorting to the SpriteKit physics engine quite yet. I'd like to keep full control on how the mechanics of the motor, clutch, transmission etc. are calculated, all the way to the RPM of the drive wheel.
From that point onwards, though, I'd happily give control to the SpriteKit physics engine, that would then calculate what happens, when the revolving drive wheel touces the surface of the road. The car advances, slows down, accelerates and/or the wheels slip, whatever the case might be.
Calculating the mechanics to get the wheel RPM is no problem. I'm just not sure on how to go on from there.
I'm able to rotate the wheel simply by applying zRotation in the update: method, like this:
self.rearWheelInstance.zRotation += (self.theCar.wheelRPS/6.283 * timeSinceLastUpdate); // revolutions / 2pi = radians
This way I'm able to apply the exact RPM I've calculated earlier. The obvious downside is, SpriteKit's physics engine is totally oblivious about this rotation. For all that it knows, the wheel teleports from one phase to the next, so it doesn't create friction with the road surface or any other interaction with other SpriteKit physicsBodies, for that matter.
On the other hand, I can apply torque to the wheel:
[self.rearWheelInstance.physicsBody applyTorque: someTorque];
or angular impulse:
[self.rearWheelInstance.physicsBody applyAngularImpulse: someAngularImpulse];
This does revolve the wheel in a fashion that SpriteKit physics engine understands, thus making it interact with its surroundings correctly.
But unless I'm missing something obvious, this considers the wheel as a 'free rolling object' independent of crankshaft, transmission or drive axel RPM. In reality, though, the wheel doesn't have the 'choice' to roll at any other RPM than what is transmitted through the drivetrain to the axel (unless the transmission is on neutral, the clutch pedal is down or the clutch is slipping, but those are whole another stories).
So:
1) Am I able to somehow manipulate zRotation in a way that the SpriteKit physics engine 'understands' as revolving movement?
or
2) Do I have a clear flaw in my logic that indicates that this isn't what I'm supposed to be trying in the first place? If so, could you be so kind as to point me to the flaw(s) so that I could adopt a better practice instead?
Simple answer, mixing 2d UI settings, like position and zRotation, with a dynamic physics system isn't going to have the results you want, as you noticed. As you state, you'll need to use the pieces of the physics simulation, like impulse and angular momentum.
The two pieces of the puzzle that may also help you are:
Physics Joints - these can do things like connect a wheel to an axel so that it can freely rotate, set limits on rotation, but still impart rotational forces on it.
Dynamically Adjusting Physics Properties - like increasing friction, angular dampening or adding negative acceleration to the axel as the user presses the brakes.
After quite a few dead ends I noticed there is in fact a way to directly manipulate the rotation of the wheel (as opposed to applying torque or impact) in a way that affects the physics engine accordingly.
The trick is to manipulate the angularVelocity property of the physicsBody of the wheel, like so:
self.rearWheelInstance.physicsBody.angularVelocity = -self.theCar.wheelRadPS;
// Wheel's angular velocity, radians per second
// *-1 just to flip ccw rotation to cw rotation
This way I'm in direct control of the drive wheels' revolving speed without losing their ability to interact with other bodies in the SpriteKit physics simulation. This helped me over this particular obstacle, I hope it helps someone else, too.

SKSpriteKit how to control Impulse or Force speed?

Hi guys i want to apply slow motion in upward direction,
what i am confused, when i applyimpulse
[self.physicsBody applyImpulse:CGVectorMake(0, 60)];
it does applyimpulse with required speed as it measure from its velocity mass and other physics things
what i need to applyImpulse but with controlling speed of impluse that is applied on object on which impulse is being applied.
i tried to set even self.speed but got no success,
how one can achieve desired impluse or Force on an sprite with controlling over speed.
are there some properties that should i set for the SKSpriteNode before applying Impulse,
or some thing else?
Any suggestion or thoughts will be appreciated
Thanks
The speed property of SKNode is to do with SKActions, however the speed property of SKPhysicsWorld is what you probably want to tweak to achieve physics in slow motion.
It says the following in the documentation about the speed property of SKPhysicsWorld
The default value is 1.0, which means the simulation runs at normal speed. A value other than the default changes the rate at which time passes in the physics simulation. For example, a speed value of 2.0 indicates that time in the physics simulation passes twice as fast as the scene’s simulation time. A value of 0.0 pauses the physics simulation.
Access it from within your SKScene subclass like this-
self.physicsWorld.speed = 0.5; // half speed (slow motion)
All forces are applied as actual physics forces on physics bodies.
The resulting movement of the body that had the force applied to it depends on not just the magnitude and direction of the force but also the size and density (i.e. mass) of the body the force is being applied to and where on the body the force is applied.
I'm not entirely sure what you mean when you say you need "controlling speed of impulse" though.
Maybe what you need is not to use forces at all but to move the node manually.
You could use an action [SKAction moveByX:y:] or update the position in the update method. This way you can control the speed of the movement exactly.

Surface Detection in 2d Game?

I'm working on a 2D Platform game, and I was wondering what's the best (performance-wise) way to implement Surface (Collision) Detection.
So far I'm thinking of constructing a list of level objects constructed of a list of lines, and I draw tiles along the lines.
alt text http://img375.imageshack.us/img375/1704/lines.png
I'm thinking every object holds the ID of the surface that he walks on, in order to easily manipulate his y position while walking up/downhill.
Something like this:
//Player/MovableObject class
MoveLeft()
{
this.Position.Y = Helper.GetSurfaceById(this.SurfaceId).GetYWhenXIs(this.Position.X)
}
So the logic I use to detect "droping/walking on surface" is a simple point (player's lower legs)-touches-line (surface) check
(with some safety approximation
- let`s say 1-2 pixels over the line).
Is this approach OK?
I`ve been having difficulty trying to find reading material for this problem, so feel free to drop links/advice.
Having worked with polygon-based 2D platformers for a long time, let me give you some advice:
Make a tile-based platformer.
Now, to directly answer your question about collision-detection:
You need to make your world geometry "solid" (you can get away with making your player object a point, but making it solid is better). By "solid" I mean - you need to detect if the player object is intersecting your world geometry.
I've tried "does the player cross the edge of this world geometry" and in practice is doesn't work (even though it might seem to work on paper - floating point precision issues will not be your only problem).
There are lots of instructions online on how to do intersection tests between various shapes. If you're just starting out I recommend using Axis-Aligned Bounding Boxes (AABBs).
It is much, much, much, much, much easier to make a tile-based platformer than one with arbitrary geometry. So start with tiles, detect intersections with AABBs, and then once you get that working you can add other shapes (such as slopes).
Once you detect an intersection, you have to perform collision response. Again a tile-based platformer is easiest - just move the player just outside the tile that was collided with (do you move above it, or to the side? - it will depend on the collision - I will leave how to do this is an exercise).
(PS: you can get terrific results with just square tiles - look at Knytt Stories, for example.)
Check out how it is done in the XNA's Platformer Starter Kit Project. Basically, the tiles have enum for determining if the tile is passable, impassable etc, then on your level you GetBounds of the tiles and then check for intersections with the player and determine what to do.
I've had wonderful fun times dealing with 2D collision detection. What seems like a simple problem can easily become a nightmare if you do not plan it out in advance.
The best way to do this in a OO-sense would be to make a generic object, e.g. classMapObject. This has a position coordinate and slope. From this, you can extend it to include other shapes, etc.
From that, let's work with collisions with a Solid object. Assuming just a block, say 32x32, you can hit it from the left, right, top and bottom. Or, depending on how you code, hit it from the top and from the left at the same time. So how do you determine which way the character should go? For instance, if the character hits the block from the top, to stand on, coded incorrectly you might inadvertently push the character off to the side instead.
So, what should you do? What I did for my 2D game, I looked at the person's prior positioning before deciding how to react to the collision. If the character's Y position + Height is above the block and moving west, then I would check for the top collision first and then the left collision. However, if the Character's Y position + height is below the top of the block, I would check the left collision.
Now let's say you have a block that has incline. The block is 32 pixels wide, 32 pixels tall at x=32, 0 pixels tall at x=0. With this, you MUST assume that the character can only hit and collide with this block from the top to stand on. With this block, you can return a FALSE collision if it is a left/right/bottom collision, but if it is a collision from the top, you can state that if the character is at X=0, return collision point Y=0. If X=16, Y=16 etc.
Of course, this is all relative. You'll be checking against multiple blocks, so what you should do is store all of the possible changes into the character's direction into a temporary variable. So, if the character overlaps a block by 5 in the X direction, subtract 5 from that variable. Accumulate all of the possible changes in the X and Y direction, apply them to the character's current position, and reset them to 0 for the next frame.
Good luck. I could provide more samples later, but I'm on my Mac (my code is on a WinPC) This is the same type of collision detection used in classic Mega Man games IIRC. Here's a video of this in action too : http://www.youtube.com/watch?v=uKQM8vCNUTM
You can try to use one of physics engines, like Box2D or Chipmunk. They have own advanced collision detection systems and a lot of different bonuses. Of course they don't accelerate your game, but they are suitable for most of games on any modern devices
It is not that easy to create your own collision detection algorithm. One easy example of a difficulty is: what if your character is moving at a high enough velocity that between two frames it will travel from one side of a line to the other? Then your algorithm won't have had time to run in between, and a collision will never be detected.
I would agree with Tiendil: use a library!
I'd recommend Farseer Physics. It's a great and powerful physics engine that should be able to take care of anything you need!
I would do it this way:
Strictly no lines for collision. Only solid shapes (boxes and triangles, maybe spheres)
2D BSP, 2D partitioning to store all level shapes, OR "sweep and prune" algorithm. Each of those will be very powerfull. Sweep and prune, combined with insertion sort, can easily thousands of potentially colliding objects (if not hundreds of thousands), and 2D space partitioning will allow to quickly get all nearby potentially colliding shapes on demand.
The easiest way to make objects walk on surfaces is to make then fall down few pixels every frame, then get the list of surfaces object collides with, and move object into direction of surface normal. In 2d it is a perpendicular. Such approach will cause objects to slide down on non-horizontal surfaces, but you can fix this by altering the normal slightly.
Also, you'll have to run collision detection and "push objects away" routine several times per frame, not just once. This is to handle situations if objects are in a heap, or if they contact multiple surfaces.
I have used a limited collision detection approach that worked on very different basis so I'll throw it out here in case it helps:
A secondary image that's black and white. Impassible pixels are white. Construct a mask of the character that's simply any pixels currently set. To evaluate a prospective move read the pixels of that mask from the secondary image and see if a white one comes back.
To detect collisions with other objects use the same sort of approach but instead of booleans use enough depth to cover all possible objects. Draw each object to the secondary entirely in the "color" of it's object number. When you read through the mask and get a non-zero pixel the "color" is the object number you hit.
This resolves all possible collisions in O(n) time rather than the O(n^2) of calculating interactions.

Resources