我正在尝试编写一个直接位于位图前面的嘴部分,但需要是一个单独的对象。
目前我的代码如下:
// 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();
显然使用以下代码会将嘴-50的x和y值放在玩家的方向上,但这只适用于1个方向,而不是将嘴保持在玩家面前:
mouth.x = player.x - 50;
mouth.y = player.y - 50;
我想知道是否有人可以帮我解决这个问题?我真的很感激。这里有2张图片可以更好地解释:
答案 0 :(得分:0)
我认为最适合您的解决方案,也将在未来帮助您,首先得到一个可靠的测试矢量库,为您完成所有这些计算。例如,你可以试试这个看起来不错的http://victorjs.org/(尽管我自己也没试过)。
一旦你有矢量工作,算法很简单:
对于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);
答案 1 :(得分:0)
@Ness的解决方案应该可以正常工作。但是,如果要避免外部依赖性,则可以使用以下内容。定义嘴矢量:
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)
这是应该绘制嘴位图的位置。