ad 1.) “我的幅度函数正确吗?”
不,您的 maginutude() 方法几乎没有错误。你的:
result = (sqrt(x*vec2.x)+(y*vec2.y));
是
result = sqrt(x*vec2.x)+(y*vec2.y);
是
result = sqrt(x*vec2.x) + (y*vec2.y);
但你可能想写这个:
result = sqrt((x*vec2.x)+(y*vec2.y));
编辑:
我最初写sqrt(x*vec2.x+y*vec2.y)是正确的,但它不是,正确的是这样:
result = sqrt(vec2.x*vec2.x + vec2.y*vec2.y);
那是因为 OP 只想计算 vec2 的大小,所以不需要使用 this.x 和 this.y。出于这个原因,我会进一步建议将您的方法更改为静态:
static float vector2D::magnitude(vector2D vec2)//<! Vector magnitude
{
return sqrt((vec2.x*vec2.x)+(vec2.y*vec2.y));
}
或仅使用实例值:
float vector2D::magnitude()//<! Vector magnitude
{
return sqrt((x*x)+(y*y));
}
在第二种情况下,您需要像这样使用magnitude() 方法:
(desiredPos - currentPos).magnitude();
补充说明:
- 此方法的结果是幅度而不是归一化(任何东西),但可用于对给定向量进行归一化。
- 此结果等于
desiredPos 和currentPos 之间的距离。
- 如果您将
(desiredPos - currentPos) 除以幅度值,您将得到归一化向量,即从currentPos 到desiredPos 的方向。
- 很明显,但如果
desiredPos 和 currentPos 相等,则幅度为零,您无法对向量进行归一化。
- 出于上述原因,我将重命名
normalisedLocation 变量。它的距离,如上所述。
Ad 2.) “我是否正确地规范了我想要的和当前的位置?”
我不确定如何理解这个问题,因为您没有对示例代码中的任何内容进行规范化。不管怎样,看看这个:
// This is from your code:
currentPos.x = laserTexture.getSize().x/2.0f;
currentPos.y = laserTexture.getSize().y/2.0f;
desiredPos.x = sf::Mouse::getPosition().x;
desiredPos.y = sf::Mouse::getPosition().y;
// Store direction to desired position. Currently length of this vector is
// distance between the two points.
vector2D dirToDesiredPos = (desiredPos - currentPos);
// Calculate distance between the two points.
float dirToDesiredPosDist = magnitude(desiredPos - currentPos);
// Detect whether the distance is zero. Problem is, you cannot compare float
// with zero (computer is not accurate enough) so we compare it with a delta
// value. It should be some small number, for example 0.01f.
// (Note that in this case we don't need to compare it with negative value -
// which would be -0.01f, because distance is always positive or zero.)
if(dirToDesiredPosDist < FLOAT_DELTA)
{
// User clicked on the tank, we cannot shoot!!!
}
else
{
// Following two lines do actuall normalization - direction of this vector
// is unchanged, but it's length is currently 1.
dirToDesiredPos.x /= dirToDesiredPosDist;
dirToDesiredPos.y /= dirToDesiredPosDist;
// Now dirToDesiredPos can be used to calculate to move your bullet to the
// desired location.
}
但仍有一个问题。如下几行:
currentPos.x = laserTexture.getSize().x/2.0f;
currentPos.y = laserTexture.getSize().y/2.0f;
这样,您可以计算激光纹理的中心,但是只有当激光在 [0, 0] 位置渲染时,该位置才是正确的。否则你需要像这样更新它:
currentPos.x = laserTexture.getSize().x/2.0f + laserPos.x;
currentPos.y = laserTexture.getSize().y/2.0f + laserPos.y;
laserPos 是您的激光当前所在的位置。