Games104作业四的基础部分和提高部分,主要完成了以下两个内容:
- 在 motor.h 中增加 control_jump_with_height 和 m_jump_speed 两个属性,用于选择性地使用玩家跳跃时的初速度来控制玩家向上跳跃的高度,同时修改 editor_ui.cpp,确保增加的属性可以正确的显示在界面上;
- 修改 MotorComponent::calculatedDesiredVerticalMoveSpeed 函数,给跳跃的控制增加使用跳跃初速度的选项;
首先在 motor.h 中增加两个属性定义,如下图所示:
调试程序后,发现 bool 值并不能在 UI 上显示出来,查看 editor.cpp 发现其中并没有实现对 bool 类型的反射支持,仿照其他数据类型的写法,在 EditorUI::EditorUI() 增加以下代码实现对 bool 类型的反射支持。
// 增加对布尔类型的处理
m_editor_ui_creator["bool"] = [this](const std::string& name, void* value_ptr) -> void {
if (g_node_depth == -1)
{
std::string label = "##" + name;
ImGui::Text("%s", name.c_str());
ImGui::SameLine();
ImGui::Checkbox(label.c_str(), static_cast<bool*>(value_ptr));
}
else
{
if (g_editor_node_state_array[g_node_depth].second)
{
std::string full_label = "##" + getLeafUINodeParentLabel() + name;
ImGui::Text("%s", (name + ":").c_str());
ImGui::Checkbox(full_label.c_str(), static_cast<bool*>(value_ptr));
}
}
};
最后,修改 motor_compent.cpp 中计算跳跃速度的定义,在计算跳跃速度时先判断使用那种方式来控制跳跃,然后采取相应的方法计算跳跃初速度。
void MotorComponent::calculatedDesiredVerticalMoveSpeed(unsigned int command, float delta_time)
{
std::shared_ptr<PhysicsScene> physics_scene =
g_runtime_global_context.m_world_manager->getCurrentActivePhysicsScene().lock();
ASSERT(physics_scene);
if (m_motor_res.m_jump_height == 0.f)
return;
const float gravity = physics_scene->getGravity().length();
if (m_jump_state == JumpState::idle)
{
if ((unsigned int)GameCommand::jump & command)
{
m_jump_state = JumpState::rising;
if (m_motor_res.control_jump_with_height)
{
m_vertical_move_speed = Math::sqrt(m_motor_res.m_jump_height * 2 * gravity);
}
else
{
m_vertical_move_speed = m_motor_res.m_jump_speed;
}
m_jump_horizontal_speed_ratio = m_move_speed_ratio;
}
else
{
m_vertical_move_speed = 0.f;
}
}
else if (m_jump_state == JumpState::rising || m_jump_state == JumpState::falling)
{
m_vertical_move_speed -= gravity * delta_time;
if (m_vertical_move_speed <= 0.f)
{
m_jump_state = JumpState::falling;
}
}
}
最终效果如下: