如何在面向方向上移动第一人称对象? (C ++)

时间:2018-03-28 15:50:45

标签: c++ math

我在Bullet中重建了一个基本的DOOM,并且想知道如何向我的对象方向移动。

目前我的框架设置在我的相机设置其旋转和位置给玩家,他的位置和旋转设置为由子弹创建的物理主体。

这是我目前为玩家运动的动作代码:

GameObject::Update( deltatime );

if( m_pController == 0 )
    return;

vec3 dir(0, 0, 0);
vec3 rot(0, 0, 0);

if( m_pController->IsButtonPressed( PCB_Up ) )
    dir.z += 1;
if( m_pController->IsButtonPressed( PCB_Down ) )
    dir.z -= 1;
if( m_pController->IsButtonPressed( PCB_Left ) )
    dir.x -= 1;
if( m_pController->IsButtonPressed( PCB_Right ) )
    dir.x += 1;
if (m_pController->IsButtonPressed(PCB_RotLeft))
    rot.y -= 1;
if (m_pController->IsButtonPressed(PCB_RotRight))
    rot.y += 1;

dir.Normalize();
rot.Normalize();

float speed = 10.0f;

btVector3 force = btVector3(dir.x, dir.y, dir.z) * speed;
btVector3 rotForce = btVector3(rot.x, rot.y, rot.z) * speed;
if( m_pBody )
{
    m_pBody->applyForce( force, btVector3(0,0,0) );
    m_pBody->applyTorque(rotForce);

    m_pBody->forceActivationState( DISABLE_DEACTIVATION );
}

我知道可以通过从相机创建矩阵并提取我的视图来完成,但事情是我的相机正在设置为我的播放器的旋转和翻译。

可以通过使用物理主体的值创建SRT矩阵并根据这些数字计算方向向量然后执行相同的操作:

if( m_pController->IsButtonPressed( PCB_Up ) )
    dir += ForwardFacing;
if( m_pController->IsButtonPressed( PCB_Down ) )
    dir -= ForwardFacing;

我不确定它是如何为左右键完成的。

反正, 谢谢你的时间!

1 个答案:

答案 0 :(得分:0)

是的,所以我最终将对象放入SRT矩阵并提取其查看位置,然后将其乘以dir.z并添加getRight以进行转动并在x轴上移动。

mat4 mat;
mat.CreateSRT(m_Scale, m_Rotation, m_Position);

vec3 forceDir = mat.GetAt() * dir.z + mat.GetRight()*dir.x;

btVector3 force = btVector3(forceDir.x, forceDir.y, forceDir.z) * speed;
btVector3 rotForce = btVector3(rot.x, rot.y, rot.z) * speed;