Cod*_*337 2 c++ 3d trigonometry angle game-physics
在我正在开发的游戏中,我获得了游戏世界对象的速度,就像这样
void getObjectVelocity(int objectID, vec3_t *velocityOut);
Run Code Online (Sandbox Code Playgroud)
所以如果我像这样调用这个函数
vec3_t storeObjectVelocity;
getObjectVelocity(21/* just an example ID */, &storeObjectVelocity);
Run Code Online (Sandbox Code Playgroud)
ID 为 21 的对象的速度将存储在storeObjectVelocity
.
出于测试目的,我试图根据游戏屏幕中间的速度打印该对象的速度。
这是一个示例,只是为了让您更好地了解我要完成的工作
int convertVelocityToSpeed(vec3_t velocity)
{
//This is where I am having issues.
//Converting the objects 3D velocity vector to a speed value
}
int testHUDS()
{
char velocityToSpeedBuffer[32] = { 0 };
vec3_t storeObjectVelocity;
getObjectVelocity(21, &storeObjectVelocity);
strcpy(velocityToSpeedBuffer, "Speed: ");
strcat(velocityToSpeedBuffer, system::itoa(convertVelocityToSpeed(storeObjectVelocity), 10));
render::text(SCREEN_CENTER_X, SCREEN_CENTER_Y, velocityToSpeedBuffer, FONT_SMALL);
}
Run Code Online (Sandbox Code Playgroud)
这是我的vec3_t
结构,以防你想知道
struct vec3_t
{
float x, y, z;
};
Run Code Online (Sandbox Code Playgroud)
向量的长度计算为 ?( x² + y² + z²)
所以在你的程序中,这样的事情会起作用:
std::sqrt( velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z )
Run Code Online (Sandbox Code Playgroud)
正如@Nelfeal 评论的那样,最后一种方法可能会溢出。std::hypot
避免使用这个问题。由于更安全,更清晰,如果 C++17 可用,这应该是第一个选项。即使知道它的效率较低。请记住避免过早的微优化。
std::hypot(velocity.x, velocity.y, velocity.z)
Run Code Online (Sandbox Code Playgroud)
此外,您应该考虑将其velocity
作为常量引用传递给函数。