Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given an angle in degrees, how can I find the logic for line of travel using x and y? (Math dilemma)

Tags:

html

math

canvas

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?

like image 269
Sabai Avatar asked Feb 15 '11 16:02

Sabai


People also ask

How do you find the X and Y angle?

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‎°)).


2 Answers

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;
like image 57
Loktar Avatar answered Sep 28 '22 01:09

Loktar


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)
like image 44
HairOfTheDog Avatar answered Sep 28 '22 03:09

HairOfTheDog