Teh Cosmic Sloth
Teh Cosmic Sloth

Reputation: 43

How To Move A Sprite "Forward" in javascript

So I'm working on a javascript game using the canvas feature in html 5 and I want to make projectiles that move toward a certain coordinate, while using a vector2 (x,y) as the velocity, is there a mathematical way to calculate the needed vector2 to produce the desired direction?

Thanks, TheCosmicSloth

Upvotes: 0

Views: 939

Answers (2)

Blindman67
Blindman67

Reputation: 54026

The simplest form is the normalised vector. A normalised vector is 1 unit long, and also called a unit vector, which you can multiply by a value to get a required speed.

start.x = ?;  // start location
start.y = ?;
dest.x = ?;  // destination
dest.y = ?;

vec.x = dest.x-start.x; // get the vector from start to dest
vec.y = dest.y-start.y;

len = Math.sqrt(vec.x * vec.x + vec.y * vec.y); //get the vec's length
vec.x /= len;  // normalise by dividing by its length
vec.y /= len; 

If you add vec to start you move one pixel at a time

start.x += vec.x;
start.y += vec.y;

If you want to move at a specific speed. Assuming frame rate of 60Fps and you want to move at 10 pixels every second

frameRate = 60; // number frames per second
speed = 10; // ten pixels per second

start.x += vec.x * (speed / frameRate);
start.y += vec.y * (speed / frameRate);

To move at specific speed with unknown frame rate.

speed = 10; // speed to move in pixels per second
time = performance.now() - lastTime; // time in ms 1000th
start.x += vec.x * (speed / time / 1000);
start.y += vec.y * (speed / time / 1000);
lastTime = performance.now();

If you want to move 100 pixels in one move

start.x += vec.x * 100;
start.y += vec.y * 100;

If you want to go backward

vec.x = -vec.x;  // reverse direction
vec.y = -vec.y;
start.x += vec.x * 100;
start.y += vec.y * 100;

To turn 90 deg clockwise

vec.x = -vec.y;
vec.y = vec.x;

To turn 90deg anticlockwise

vec.x = vec.y;
vec.y = -vec.x;

To create a vector at an angle. Angle is in radians. 0 points from left to right of screen. positive values turn clockwise.

angle = ?
vec.x = Math.cos(angle);  // Creates a normalised vector
vec.y = Math.sin(angle);

To convert a vector to an angle

angle = Math.atan2(vec.y,vec.x); // The Y is first
                                 // angle in radians.

Upvotes: 1

Bricky
Bricky

Reputation: 2745

What you're looking for is called the slope of a line. Take the difference in x divided by the difference in y.

This will tell you that for every unit you move along the x axis, the ratio of units along the y axis you must move in order to maintain your heading.

See Wikipedia

Upvotes: 0

Related Questions