簡體   English   中英

C++ 將 3D 速度向量轉換為速度值

[英]C++ Convert 3D Velocity Vector To Speed Value

在我正在開發的游戲中,我獲得了游戲世界對象的速度,就像這樣

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

向量的長度計算為 √( 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作為對函數的常量引用傳遞。

速度是由速度矢量|velocity|的大小給出的標量|velocity| . 3D 矢量的大小計算如下:

矢量的大小

因此,在您的代碼中,您希望將方法實現為:

int convertVelocityToSpeed(vec3_t velocity)
{
    return std::sqrt(velocity.x * velocity.x + velocity.y * velocity.y + velocity.z * velocity.z);
}

您可能需要包含數學頭文件#include <cmath>並且我假設您的vec3_t包含int值,盡管這對於物理模擬中的速度來說是不尋常的,它們通常是浮點類型。 如果不是,您需要檢查您的退貨類型。

#include <cmath>

using namespace std;

sqrt(pow(velocity.x,2), pow(velocity.y,2), pow(velocity.x,2));

使用 cmath 中的 sqrt 和 cmath 中的 pow。

編輯編輯了錯誤輸入,如評論中所糾正

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM