#### Archived

This topic is now archived and is closed to further replies.

# change direction velocity

This topic is 5450 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Hi, I''m having a problem getting my head around changing direction of my object(a car). It has an x and y co-ordinate, and a x velocity, and y velocity. I also have a speed. How do I work out the x and y velocities when they change when the left and right keys are changed? Many thanks Nick Swan

##### Share on other sites
Let''s talk about acceleration.

When no keys are being pressed, the car moves at a constant speed. It does not accelerate (or decelerate, which is negative acceleration).

When a key is pressed, an acceleration happens. The velocity changes more the longer you hold the key.

If at the moment you have
x+=vx*timeStepThisFrame;y+=vy*timeStepThisFrame;

then all you need to add is
vx+=ax*timeStepThisFrame;vy+=ay*timeStepThisFrame;

and you set ''ax'' and ''ay'' depending on the direction you want to accelerate in.

If you want to go even further, you can use the equation

F=ma

to calculate the accleration based on the mass of the car and the force the engine is applying to it... though a car turning is a little different to traditional ''car-crash'' physics, if that''s what you''re aiming for.

Superpig
- saving pigs from untimely fates, and when he''s not doing that, runs The Binary Refinery.
Enginuity1 | Enginuity2 | Enginuity3 | Enginuity4

##### Share on other sites
It''s when the car is turning that i have a problem. I''ve tried using code found from LaMothes book:

//in game innit
// create the 16 sector sin, cos lookup
int ang;
for (ang=0; ang < 16; ang++)
{
float fang = PI*(ang*22.5)/180;

cos_look16[ang] = -cos(fang+PI/2);
sin_look16[ang] = -sin(fang+PI/2);

} // end for ang

//in game main
//change the speed of the car
if(KEY_DOWN(VK_UP))
cars[0].speed = 1;
else
{
cars[0].speed = 0;
}

//change the y and x velocities

if(KEY_DOWN(VK_LEFT))
{
if(--cars[0].direction < 0)
cars[0].direction = 15;
}

if(KEY_DOWN(VK_RIGHT))
{
if(++cars[0].direction > 15)
cars[0].direction = 0;
}

if(cars[0].speed == 1)
{
cars[0].yv = sin_look16[cars[0].direction] * cars[0].speed;
cars[0].y =cars[0].y - cars[0].yv;

cars[0].xv = cos_look16[cars[0].direction] * cars[0].speed;
cars[0].x = cars[0].x - cars[0].xv;
}

unfortunately the car doesn''t move forwards or backwards let alone left or right!

1. 1
2. 2
Rutin
22
3. 3
JoeJ
18
4. 4
5. 5

• 15
• 40
• 23
• 13
• 13
• ### Forum Statistics

• Total Topics
631725
• Total Posts
3001905
×