gpt4 book ai didi

C++ 将 3D 速度 vector 转换为速度值

转载 作者:行者123 更新时间:2023-11-30 01:05:14 27 4
gpt4 key购买 nike

在我正在开发的游戏中,我得到了游戏世界对象的速度

void getObjectVelocity(int objectID, vec3_t *velocityOut);

所以如果我像这样调用这个函数

vec3_t storeObjectVelocity;
getObjectVelocity(21/* just an example ID */, &storeObjectVelocity);

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

如果您想知道的话,这是我的 vec3_t 结构

struct vec3_t
{
float x, y, z;
};

最佳答案

vector 的长度计算为√( x² + y² + z²)

所以在你的程序中,像这样的东西会起作用:

std::sqrt( velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z )

正如@Nelfeal 评论的那样,最后一种方法可能会溢出。使用std::hypot这个问题就避免了。由于更安全也更清晰,如果 C++17 可用,这应该是第一个选项。即使知道它的效率较低。请记住避免过早的微优化。

std::hypot(velocity.x, velocity.y, velocity.z)

此外,您应该考虑将 velocity 作为函数的 const 引用传递。

关于C++ 将 3D 速度 vector 转换为速度值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48943163/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com