2016-07-13 25 views
1

我試圖編寫一個嘴部分,它將直接停留在位圖的前部,但需要成爲一個單獨的對象。Javascript - 如何讓對象直接停留在另一個之前?

目前我的代碼看起來是這樣的:

// LOCATION: 
    var xDistance = stage.getStage().mouseX - player.x; 
    var yDistance = stage.getStage().mouseY - player.y; 
    var distance = Math.sqrt(xDistance * xDistance + yDistance * yDistance); 
    var x = player.x += xDistance * easingAmount; 
    var y = player.y += yDistance * easingAmount; 

    if (distance > 1) { 
    player.x += xDistance * easingAmount; 
    player.y += yDistance * easingAmount; 
    } 

    // ROTATION: 
    var degrees = (Math.atan2(yDistance, xDistance) * 180/Math.PI) - 90; 
    if(degrees >= 360) { 
    degrees -= 360; 
    } 

    player.rotation = degrees; 
    stage.update(); 

顯然使用下面的代碼將放置在X和播放機的方向口-50的y值,但對於1個方向這隻能代替保持在播放器前的嘴:

mouth.x = player.x - 50; 
    mouth.y = player.y - 50; 

我想知道是否有人可以幫助我這個數學?我真的很感激。這裏有兩個圖像,以便更好地解釋事情:

enter image description here

enter image description here

+0

它真的很難理解你想要的東西......你想讓玩家保持距離嘴巴不變的距離並隨之旋轉嗎? –

+0

這與數學有什麼關係? – duffymo

+0

@Ness是的,那正是我要找的。 – Skua

回答

0

我認爲最適合您的解決方案,這也將幫助你在未來,是先得到一個堅實的測試向量庫爲你做所有這些計算。例如,你可以試試這個看起來不錯的http://victorjs.org/(儘管我自己沒有嘗試過)。

一旦你有向量工作,算法很簡單:

  1. 獲取作爲一個角度或弧度播放機的方向。
  2. 從那個角度創建一個向量。
  3. 將該向量乘以所需的距離。
  4. 嘴巴或其他部分的位置是玩家+矢量的位置。

隨着victorjs它會是這樣的(未測試):

// who the hell calls his "Vector" class "Victor"? alias it. 
var Vector = Victor; 

// create the vector from player angle (assume player_angle is defined somewhere) 
var v = new Vector(1, 0); 
v = v.rotateDeg(player_angle); 

// multiply by desired distance, assume its 20 pixels 
v = v.multiply(new Vector(20, 20)); 

// now calc mouth position (assume player_pos is defined before) 
var mouth_pos = player_pos.add(mouth_pos); 
+0

感謝您的回覆。我目前使用EaselJS創建位圖。口部分和播放器都是用這個庫創建的位圖。如果我已經有了所有這些計算,我是否需要VectorJS?只是一個想法。儘管我非常感謝你的幫助。 – Skua

+0

正如你所看到的,我使用這一行:var degrees =(Math.atan2(yDistance,xDistance)* 180/Math。PI) - 90;來計算玩家的角度。我所需要做的就是弄清楚如何讓嘴巴準確地微調玩家,只有它前面的幾個像素。 – Skua

0

@內斯的解決方案應該很好地工作。但是,如果您想避免外部依賴性,以下方法可能會起作用。定義口載體:

mouth.x = 50; 
mouth.y = 0; // The mouth is the distance 50 away from the player. 
      // Assuming that a non-rotated player points in the x- 
      // direction 
rotateVector(mouth, player.rotation); 

而且你可以定義rotateVector爲(見wikipedia

function rotateVector(var vec, var degrees) { 
    var output; // of vector type 
    output.x = cos(degrees)*vec.x - sin(degrees)*vec.y; 
    output.y = sin(degrees)*vec.x + cos(degrees)*vec.y; 
    return output; 
} 

嘴的世界空間中的位置現在是

mouthWorldSpace = player.position + mouth.position; // (i.e. just add the vectors together) 

這是位置應該繪製嘴部位圖。

+0

非常感謝您的回覆。不過,我想我已經有了這些計算。正如我對@Ness所說的,我真的只是想讓嘴巴位圖準確地模仿玩家的行爲。另外,我已經有一個叫做EaselJS的外部依賴(應該可能在OP中提到過)。 – Skua

+0

@Skua然後我不確定問題是什麼(我添加了3條線,我意識到我錯過了 - 是你在找什麼?)。這種方法應該正確地給你嘴的位置(你可以渲染爲位圖或其他任何東西) – pingul

+0

乾杯 - 我會給你一個鏡頭:) – Skua

相關問題