How to handle SpriteKit frame rate drop when multiplying by delta time - ios7

I use a common method of multiplying a player velocity in delta time in order to create gravitation effect as follows:
CGPoint gravity = CGPointMake(0, kGravity);
CGPoint gravityStep = CGPointMultiplyScalar(gravity, _dt);
_playerVelocity = CGPointAdd(_playerVelocity, gravityStep);
CGPoint velocityStep = CGPointMultiplyScalar(_playerVelocity, _dt);
_player.position = CGPointAdd(_player.position, velocityStep);
The problem is that when the frame rate drops (for example - when getting a notification not related to the game) the player misses the jump, I am guessing due to missed updates, and falls.
Is there a proper way to deal with this usecase?

You are factoring in delta time twice! This is not a framerate drop but your nodes moving faster than they should. Removing the 2nd line should fix it.

Related

How could I make an "iPod Wheel" type control on iPhone?

I want to create a sort of "iPod Wheel" control in a Swift project that I'm doing. I've got everything drawn out, but not it's time to actually make this thing work.
What would be the best way to recognize "spinning" so to speak, or to describe that more clearly, when the user is actively pressing the wheel and spinning his/her thumb around the wheel in a clockwise or counter-clockwise direction.
I will no doubt want to use touchesBegan/touchesMoved/touchesEnded. What's the best way to figure out spinning though?
I'm thinking
a) determine in touchesMoved if the users touch is within circle, by determining the radius from the center point. Center point and radius are easily obtainable. Using these however, how can I determine the outer edge of the circle/wheel... to know whether the user is within the actually circle (their touch could still be in the view, but outside the actual wheel portion)
b) Determine the current angle and how it has changed the previous angle. By that I mean... I would use the center point of the circle as one point, and the users current touch as the second point. This gives me my vector. I would also have a baseline angle. Likely center point to 12 c'clock. I would compare the two vectors (I already have a VectorMath class for this from something else I'm doing) and see my angle is 0. If the users touch were at 3 oclock, and I compared it to our baseline angle... I would see the angle is 90 degrees. I would continually calculate the angle, and perhaps every 5 degrees of change... would warrant a change in the controls output (depending on desired sensitivity).
Does this seem like the best way to do this? I think this would be an ideal way, but am still not sure on how to calculate the circles outer edge, and determine if a users touch is within it.
You are on the right track. I think approach b) will work.
Remember the starting position of the finger at the touchesBegan
event.
Imagine a line from the finger position to the middle of the button
circle.
For the touchesMoved event, again, imagine a virtual line from the
new position to the center of the circle.
Using the formula from
http://mathworld.wolfram.com/Line-LineAngle.html (or some code) you can determine
the angle between the two lines. If it's a negative angle the user
is turning the wheel counter-clockwise, otherwise it's clockwise.
To determine if the touch event was inside the ring, calculate the distance from the center of the circle to the point of touch. It should be between the minimum and the maximum distance (inner circle and outer circle radius). Calculating the distance between to two points is explained at https://www.mathsisfun.com/algebra/distance-2-points.html
I think you're almost there, although I'd do something slightly different on your point b.
If you think about it, when you start "spinning" on your iPod, you don't need to start from a precise position, you start spinning from "where you started", therefore I wouldn't set my "baseline angle" at π/2, I'd set my baseline (or 0°) angle at the point the user taps for the first time, and starting from then, I'd count the offset angles, clockwise and counterclockwise.
I don't think there would be much difference, except maybe from some calculations you'll do on the angles, on the two approaches, practically speaking; it just makes more sense imho to start counting from the first input rater than setting a baseline to π/2 and counting the first angle.
I am answering in parts.
// Get a position based on the angle
float xPosition = center.x + (radiusX * sinf(angleInRadians)) - (CGRectGetWidth([cell frame]) / 2);
float yPosition = center.y + (radiusY * cosf(angleInRadians)) - (CGRectGetHeight([cell frame]) / 2);
float scale = 0.75f + 0.25f * (cosf(angleInRadians) + 1.0);
next
[cell setTransform:CGAffineTransformScale(CGAffineTransformMakeTranslation(xPosition, yPosition), scale, scale)];
// Tweak alpha using the same system as applied for scale, this
// time with 0.3 the minimum and a semicircle range of 0.5
[cell setAlpha:(0.3f + 0.5f * (cosf(angleInRadians) + 1.0))];
and
- (void)spin:(SpinGestureRecognizer *)recognizer
{
CGFloat angleInRadians = -[recognizer rotation];
CGFloat degrees = 180.0 * angleInRadians / M_PI; // Radians to degrees
[self setCurrentAngle:[self currentAngle] + degrees];
[self setAngle:[self currentAngle]];
}
again check the wheelview.m of photowheel in github.

How can I move a CCNode along an arc, with linear animation speed?

I'm trying to animate a CCNode in a semi circle motion and have it constantly move at the same speed. I thought I could achieve this with Bezier animation.
I'm trying to find the correct implementation to run an action with CCActionBezierBy (ref) that will not have an ease rate at all.
CGFloat duration = 5;
// bezierConfig is already set
CGFloat rate = 0.0f;
id action = [CCActionBezierBy actionWithDuration:duration bezier:bezierConfig];
id ease = [CCActionEaseRate actionWithAction:action rate:rate];
id spawn = [CCActionSpawn actions:action, ease, nil];
As I manipulate the rate I can see results, with 0 being the lowest ease animation. But how can I make the animation completely linear?
Place moving node in parent node. Its coordinates from parent root will be moving radius. Then make 2 rotation actions. One rotation of parent with constant speed. And rotation of node itself to the opposite direction.

applyForce(0, 400) - SpriteKit inconsistency

So I have an object that has a physicsBody and gravity affects it. It is also dynamic.
Currently, when the users touches the screen, I run the code:
applyForce(0, 400)
The object moves up about 200 and then falls back down due to gravity. This only happens some of the time. Other times, it results in the object only moving 50ish units in the Y direction.
I can't find a pattern... I put my project on dropbox so it can be opened if anyone is willing to look at it.
https://www.dropbox.com/sh/z0nt79pd0l5psfg/bJTbaS2JpY
EDIT: It seems this happens when the player is bouncing off of the ground slightly for a moment after impact. Is there a way I can make it so the player doesn't bounce at all?
EDIT 2: I tried to solve this using the friction parameter and only allowing the player to "jump" when the friction was = 0 (you would think this would be all cases where the player was airborne) but friction appears to be greater than 0 at all times. How else might I detect if the player is touching an object (other than by using the y location)?
Thanks
Suggested Solution
If you're trying to implement a jump feature, I suggest you look at applyImpulse instead of applyForce. Here's the difference between the two, as described in the Sprite Kit Programming Guide:
You can choose to apply either a force or an impulse:
A force is applied for a length of time based on the amount of simulation time that passes between when you apply the force and when the next frame of the simulation is processed. So, to apply a continuous force to an body, you need to make the appropriate method calls each time a new frame is processed. Forces are usually used for continuous effects.
An impulse makes an instantaneous change to the body’s velocity that is independent of the amount of simulation time that has passed. Impulses are usually used for immediate changes to a body’s velocity.
A jump is really an instantaneous change to a body's velocity, meaning that you should apply an impulse instead of a force. To use the applyImpulse: method, figure out the desired instantaneous change in velocity, multiply by the body's mass, and use that as the impulse parameter into the function. I think you'll see better results.
Explanation for Unexpected Behavior
If you're calling applyForce: outside of your update: function, what's happening is that your force is being multiplied by the amount of time passed between when you apply the force and when the next frame of the simulation is processed. This multiplier is not a constant, so you're seeing a different change in velocity every time you call applyForce: in this manner.
#godel9 has a good suggested solution, although, in my own testing, the explanation given for the unexpected behaviour is not correct.
From the SKPhysicsBody Class Reference:
The force is applied for a single simulation step (one frame).
Referring back to the SKScene Class Reference's section on the -update method:
...it is called exactly once per frame, so long as the scene is presented in a view and is not paused.
So we can assume that calling -applyForce: in SKScene's -update method should not cause a problem. But as observed, the force does not exceed gravity, despite applying an upward force much greater than gravity (400 newtons vs 9.81).
I created a test project that would create two nodes, one that falls naturally, setting affectedByGravity to TRUE, and another that calls -applyForce with the same expected gravity vector (0 newtons in the x direction, and -9.81 in the y direction). I then calculated the difference in velocity of each node in one time step, and the length of time step. From this, I then logged the acceleration (change in velocity / change in time).
Here is a snippet from my SKScene subclass:
- (id)initWithSize:(CGSize)size
{
if (self = [super initWithSize:size])
{
self.backgroundColor = [UIColor purpleColor];
SKShapeNode *node = [[SKShapeNode alloc] init];
node.path = CGPathCreateWithEllipseInRect(CGRectMake(0, 0, 10, 10), nil);
node.name = #"n";
node.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:5];
node.position = CGPointMake(0, 450);
node.physicsBody.linearDamping = 0;
node.physicsBody.affectedByGravity = NO;
[self addChild:node];
node = [[SKShapeNode alloc] init];
node.path = CGPathCreateWithEllipseInRect(CGRectMake(0, 0, 10, 10), nil);
node.name = #"n2";
node.physicsBody = [SKPhysicsBody bodyWithCircleOfRadius:5];
node.position = CGPointMake(20, 450);
node.physicsBody.linearDamping = 0;
[self addChild:node];
}
return self;
}
- (void)update:(NSTimeInterval)currentTime
{
SKNode *node = [self childNodeWithName:#"n"];
SKNode *node2 = [self childNodeWithName:#"n2"];
CGFloat acc1 = (node.physicsBody.velocity.dy - self.previousVelocity) / (currentTime - self.previousTime);
CGFloat acc2 = (node2.physicsBody.velocity.dy - self.previousVelocity2) / (currentTime - self.previousTime);
[node2.physicsBody applyForce:CGVectorMake(0, node.physicsBody.mass * -150 * self.physicsWorld.gravity.dy)];
NSLog(#"x:%f, y:%f, acc1:%f, acc2:%f", node.position.x, node.position.y, acc1, acc2);
self.previousVelocity = node.physicsBody.velocity.dy;
self.previousTime = currentTime;
self.previousVelocity2 = node2.physicsBody.velocity.dy;
}
The results are unusual. The node that is affected by gravity in the simulation has an acceleration that is consistently multiplied by a factor of 150 when compared to the node whose force was manually applied. I have attempted this with nodes of varying size and density, but the same scalar multiplier exists.
From this I must deduce that SpriteKit internally has a default 'pixel-to-meter' ratio. That is to say that each 'meter' is equal to exactly 150 pixels. This is sometimes useful, as otherwise the scene is often too large, meaning forces react slowly (think watching an airplane from the ground, it is travelling very fast but seemingly moving very slowly).
Sprite Kit documentation frequently suggests that exact physics calculations are not recommended (seen specifically in the section 'Fudging the Numbers'), but this inconsistency took me a long time to pin down. Hope this helps!

gravity simulation

I want to simulate a free fall and a collision with the ground (for example a bouncing ball). The object will fall in a vacuum - an air resistance can be omitted. A collision with the ground should causes some energy loss so finally the object will stop moving. I use JOGL to render a point which is my falling object. A gravity is constant (-9.8 m/s^2).
I found an euler method to calculate a new position of the point:
deltaTime = currentTime - previousTime;
vel += acc * deltaTime;
pos += vel * deltaTime;
but I'm doing something wrong. The point bounces a few times and then it's moving down (very slow).
Here is a pseudocode (initial pos = (0.0f, 2.0f, 0.0f), initial vel(0.0f, 0.0f, 0.0f), gravity = -9.8f):
display()
{
calculateDeltaTime();
velocity.y += gravity * deltaTime;
pos.y += velocity.y * deltaTime;
if(pos.y < -2.0f) //a collision with the ground
{
velocity.y = velocity.y * energyLoss * -1.0f;
}
}
What is the best way to achieve a realistic effect ? How the euler method refer to the constant acceleration equations ?
Because floating points dont round-up nicely, you'll never get at a velocity that's actually 0. You'd probably get something like -0.00000000000001 or something.
you need to to make it 0.0 when it's close enough. (define some delta.)
To expand upon my comment above, and to answer Tobias, I'll add a complete answer here.
Upon initial inspection, I determined that you were bleeding off velocity to fast. Simply put, the relationship between kinetic energy and velocity is E = m v^2 /2, so after taking the derivative with respect to velocity you get
delta_E = m v delta_v
Then, depending on how energyloss is defined, you can establish the relationship between delta_E and energyloss. For instance, in most cases energyloss = delta_E/E_initial, then the above relationship can be simplified as
delta_v = energyloss*v_initial / 2
This is assuming that the time interval is small allowing you to replace v in the first equation with v_initial, so you should be able to get away with it for what your doing. To be clear, delta_v is subtracted from velocity.y inside your collision block instead of what you have.
As to the question of adding air-resistance or not, the answer is it depends. For small initial drop heights, it won't matter, but it can start to matter with smaller energy losses due to bounce and higher drop points. For a 1 gram, 1 inch (2.54 cm) diameter, smooth sphere, I plotted time difference between with and without air friction vs. drop height:
For low energy loss materials (80 - 90+ % energy retained), I'd consider adding it in for 10 meter, and higher, drop heights. But, if the drops are under 2 - 3 meters, I wouldn't bother.
If anyone wants the calculations, I'll share them.

Ball to Ball Collision - Gains significant velocity upon collision

I implemented the code from the question "Ball to Ball Collision - Detection and Handling" in Objective-C. However, whenever the balls collide at an angle their velocity increases dramatically. All of the vector math is done using cocos2d-iphone, with the header CGPointExtension.h. What is the cause of this undesired acceleration?
The following is an example of increase in speed:
Input:
mass == 12.56637
velocity.x == 1.73199439
velocity.y == -10.5695238
ball.mass == 12.56637
ball.velocity.x == 6.04341078
ball.velocity.y == 14.2686739
Output:
mass == 12.56637
velocity.x == 110.004326
velocity.y == -10.5695238
ball.mass == 12.56637
ball.velocity.x == -102.22892
ball.velocity.y == -72.4030228
#import "CGPointExtension.h"
#define RESTITUTION_CONSTANT (0.75) //elasticity of the system
- (void) resolveCollision:(Ball*) ball
{
// get the mtd (minimum translation distance)
CGPoint delta = ccpSub(position, ball.position);
float d = ccpLength(delta);
// minimum translation distance to push balls apart after intersecting
CGPoint mtd = ccpMult(delta, (((radius + ball.radius)-d)/d));
// resolve intersection --
// inverse mass quantities
float im1 = 1 / [self mass];
float im2 = 1 / [ball mass];
// push-pull them apart based off their mass
position = ccpAdd(position, ccpMult(mtd, (im1 / (im1 + im2))));
ball.position = ccpSub(ball.position, ccpMult(mtd, (im2 / (im1 + im2))));
// impact speed
CGPoint v = ccpSub(velocity, ball.velocity);
float vn = ccpDot(v,ccpNormalize(mtd));
// sphere intersecting but moving away from each other already
if (vn > 0.0f) return;
// collision impulse
float i = (-(1.0f + RESTITUTION_CONSTANT) * vn) / ([self mass] + [ball mass]);
CGPoint impulse = ccpMult(mtd, i);
// change in momentum
velocity = ccpAdd(velocity, ccpMult(impulse, im1));
ball.velocity = ccpSub(ball.velocity, ccpMult(impulse, im2));
}
Having reviewed the original code and the comments by the original poster, the code seems the same, so if the original is a correct implementation, I would suspect a bad vector library or some kind of uninitialized variable.
Why are you adding 1.0 to the coefficient of restitution?
From: http://en.wikipedia.org/wiki/Coefficient_of_restitution
The COR is generally a number in the range [0,1]. Qualitatively, 1 represents a perfectly elastic collision, while 0 represents a perfectly inelastic collision. A COR greater than one is theoretically possible, representing a collision that generates kinetic energy, such as land mines being thrown together and exploding.
Another problem is this:
/ (im1 + im2)
You're dividing by the sum of the reciprocals of the masses to get the impulse along the vector of contact - you probably should be dividing by the sum of the masses themselves. This is magnifying your impulse ("that's what she said").
I'm the one who wrote the original ball bounce code you referenced. If you download and try out that code, you can see it works fine.
The following code is correct (the way you originally had it):
// collision impulse
float i = (-(1.0f + RESTITUTION_CONSTANT) * vn) / (im1 + im2);
CGPoint impulse = ccpMult(mtd, i);
This is very common physics code and you can see it nearly exactly implemented like this in the following examples:
Find collision response of two objects - GameDev
3D Pong Collision Response
Another ball to ball collision written in Java
This is correct, and it ~isn't~ creating a CoR over 1.0 like others have suggested. This is calculating the relative impulse vector based off mass and Coefficient of Restitution.
Ignoring friction, a simple 1d example is as follows:
J = -Vr(1+e) / {1/m1 + 1/m2}
Where e is your CoR, Vr is your normalized velocity and J is a scalar value of the impulse velocity.
If you plan on doing anything more advanced than this I suggest you use one of the many physics libraries already out there. When I used the code above it was fine for a few balls but when I ramped it up to several hundred it started to choke. I've used the Box2D physics engine and its solver could handle more balls and it is much more accurate.
Anyway, I looked over your code and at first glance it looks fine (it is a pretty faithful translation). It is probably a small and subtle error of a wrong value being passed in, or a vector math problem.
I don't know anything concerning iPhone development but I would suggest setting a breakpoint at the top of that method and monitoring each steps resulting value and finding where the blow-up is. Ensure that the MTD is calculated correctly, the impact velocities, etc, etc until you see where the large increase is getting introduced.
Report back with the values of each step in that method and we'll see what we have.
In this line:
CGPoint impulse = ccpMult(mtd, i);
mtd needs to have been normalised. The error happened because in the original code mtd was normalized in a previous line but not in your code. You can fix it by doing something like this:
CGPoint impulse = ccpMult(ccpNormalize(mtd), i);