2016-10-29 5 views
0

私はhtml 5でキャンバス機能を使用しているjavascriptゲームで作業していますが、vector2(x、y )を必要とするベクトル2を計算する数学的方法がありますか?JavaScriptでスプライト "前方"を移動する方法

おかげで、あなたは直線の傾きと呼ばれて探しているものを TheCosmicSloth

答えて

0

xの差をyの差で割ってください。

これは、x軸に沿って移動するすべてのユニットについて、y軸に沿ったユニットの比率を、あなたの見出しを維持するために移動する必要があることを示します。

See Wikipedia

+0

角度にベクトルを変換します –

0

最も単純な形態は、正規化ベクトルです。正規化されたベクトルは1単位の長さで、単位ベクトルとも呼ばれ、必要な速度を得るために値を掛けることができます。あなたが特定の速度で移動する場合は、時間

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

に1ピクセルずつ移動vecstartに追加した場合

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; 

。フレームレートが60Fpsと仮定し、毎秒10ピクセルで移動したい場合

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

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

未知のフレームレートで特定の速度で移動する場合。

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(); 

あなたはあなたに90度時計回り

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

を有効にするには、後方

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

に行きたい場合は一手

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

に100個のピクセルを移動したい場合反時計回りに90度回す

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

斜めにベクトルを作成するには:角度はラジアンです。画面の左から右に0点。正の値は時計回りに回ります。

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

ワウ私は代数方程式とy = MX + B忘れXD今愚か感じる

angle = Math.atan2(vec.y,vec.x); // The Y is first 
           // angle in radians. 
関連する問題