开发者

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

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 logi开发者_C百科c can I use if the angle is say, 32?


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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜