I am making a simple game in HTML5 canvas, it involves driving a little car.
The up arrow moves the car, the left and right arrow steers it.
I have rotation sorted, but now it needs to move its x and y position when holding the up key, based on what angle it is at.
Example:
Angle is 0, the up arrow will only affect the y coordinate.
Angle is 45, the up arrow will affect both x and y coordinates at an equal pace.
What logic can I use if the angle is say, 32?
Typically, to find the x, y coordinates on a circle with a known radius and angle you could simply use the formula x = r(cos(degrees°)), y = r(sin(degrees°)).
You could try something like this
velY = Math.cos(angle * Math.PI / 180) * thrust;
velX = Math.sin(angle * Math.PI / 180) * thrust;
x += velX;
y -= velY;
Quick example, angle is just incremented every loop.
http://jsfiddle.net/j5U5h/5/
Angle 0 is up like you have in your initial question.
Here is the jsfiddle modified so the angle of 0 moves you to the right.
http://jsfiddle.net/j5U5h/7/
velX = Math.cos(angle * Math.PI / 180) * thrust;
velY = Math.sin(angle * Math.PI / 180) * thrust;
x += velX;
y += velY;
To make 0 go to the right initially just change to this,
velX = -Math.cos(angle * Math.PI / 180) * thrust;
Did you really mean that 90 moves both axes equally? It seems to me that it should be 45 moves both axes equally.
if 45 moves both axes equally:
xfactor = angle * (1/90)
yfactor = (90 - angle) * (1/90)
xpos = xpos + (xincrement * xfactor)
ypos = ypos + (yincrement * yfactor)
if 90 moves both axes equally:
xfactor = (2 * angle) * (1/180)
yfactor = (180 - (2 * angle)) * (1/180)
xpos = xpos + (xincrement * xfactor)
ypos = ypos + (yincrement * yfactor)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With