dev6546
dev6546

Reputation: 1442

Change speed depending on angular velocity

I scroll my background at a speed value of float speed = 50; I want to change this speed value depending on the angle of my sprite on the background, so it looks like the sprite is slowing down when it turns corners. All my accessors and mutators are set up, I just can't work out the formula which alters the background speed depending on the sprites angular velocity.

here is my mutator, whatever formula I use to give me value it'll be taken off every tick in my update method like this:

-(void) setSpeed:(float) value
{
    Speed -= value;
}

Then to actually get the background moving I use:

-(void) update:(ccTime)delta
{
    if (background.position.y < background2.position.y)
    {
        background.position = ccp(background.contentSize.width / 2, background.position.y - speed * delta);
        background2.position = ccp(background.contentSize.width / 2, background.position.y + background.contentSize.height);
    }
    else
    {
        background2.position = ccp(background2.contentSize.width / 2, background2.position.y - speed * delta);
        background.position = ccp(background2.contentSize.width / 2, background2.position.y + background.contentSize.height);
    }

    //reset
    if (background.position.y <-background.contentSize.height / 2)
    {
        background.position = ccp(background.contentSize.width / 2 ,background2.position.y + background2.contentSize.height);
    } 
    else if (background2.position.y < -background2.contentSize.height / 2)
    {
        background2.position = ccp(background2.contentSize.width / 2, background.position.y + background.contentSize.height);
    }
}

Any ideas?

EDIT:

I suppose a better way of doing this would be to make the speed value of the background be determined completely on a formula generated by the player sprites rotation, rather than me initialising speed at 50 to begin with, any thoughts for the formula?

Upvotes: 0

Views: 541

Answers (1)

MechEthan
MechEthan

Reputation: 5703

Math time! :D

What you want is to find the y-component of a rotated vector. The vector has magnitude equal to your velocity (aka speed).

Ye olde reminder: SOH-CAH-TOA!

We'll want to use the CAH: Cosine(angleInRadians) = Adjacent / Hypotenuse ... In this case, the angle is known (the sprites rotation), the Hypotenuse is known (the sprite's simulated speed), and the Adjacent is the unknown speed of your background in the y direction. So, we solve for "Adjacent" ...

On to the code:

float spriteSpeed = 50.0;
...
float radians = -CC_DEGREES_TO_RADIANS(yourSprite.rotation);
float backgroundYSpeed = cosf(radians) * spriteSpeed;

You could also simultaneously shift your background horizontally using Sine:

float backgroundXSpeed = sinf(radians) * spriteSpeed;

Upvotes: 1

Related Questions