Skip to content

Instantly share code, notes, and snippets.

@gleblebedev
Created April 29, 2022 10:34
Show Gist options
  • Save gleblebedev/542dcecaa8d3d1901dfc2e39a39c230a to your computer and use it in GitHub Desktop.
Save gleblebedev/542dcecaa8d3d1901dfc2e39a39c230a to your computer and use it in GitHub Desktop.
Urho3D FreeCamera
//обязательно присвойте yaw первоначальное значение
REApplication::REApplication(Urho3D::Context* context)
: Application(context),
yaw_(0.0f),
pitch_(0.0f)
{
}
void REApplication::Start()
{
CreateConsoleAndDebugHud();
// Create scene providing a colored background.
CreateScene();
// Finally subscribe to the update event. Note that by subscribing events at this point we have already missed some events
// like the ScreenMode event sent by the Graphics subsystem when opening the application window. To catch those as well we
// could subscribe in the constructor instead.
SubscribeToEvents();
// Pass console commands to file system.
GetSubsystem<FileSystem>()->SetExecuteConsoleCommands(true);
GetSubsystem<Console>()->RefreshInterpreters();
}
void REApplication::SubscribeToEvents()
{
SubscribeToEvent(E_UPDATE, URHO3D_HANDLER(REApplication, OnUpdate));
}
void REApplication::OnUpdate(StringHash, VariantMap& eventData)
{
float deltaTime = eventData[Update::P_TIMESTEP].GetFloat();
MoveCamera(deltaTime);
}
void REApplication::MoveCamera(float deltaTime)
{
if (GetSubsystem<UI>()->GetFocusElement())
return;
auto* input = GetSubsystem<Input>();
// Movement speed as world units per second
const float MOVE_SPEED = 20.0f;
// Mouse sensitivity as degrees per pixel
const float MOUSE_SENSITIVITY = 0.1f;
// Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees
IntVector2 mouseMove = input->GetMouseMove();
yaw_ += MOUSE_SENSITIVITY * mouseMove.x_;
pitch_ += MOUSE_SENSITIVITY * mouseMove.y_;
pitch_ = Clamp(pitch_, -90.0f, 90.0f);
// Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero
cameraNode_->SetRotation(Quaternion(pitch_, yaw_, 0.0));
// Read WASD keys and move the camera scene node to the corresponding direction if they are pressed
if (input->GetKeyDown(KEY_W))
cameraNode_->Translate(Vector3::FORWARD * MOVE_SPEED * deltaTime);
if (input->GetKeyDown(KEY_S))
cameraNode_->Translate(Vector3::BACK * MOVE_SPEED * deltaTime);
if (input->GetKeyDown(KEY_A))
cameraNode_->Translate(Vector3::LEFT * MOVE_SPEED * deltaTime);
if (input->GetKeyDown(KEY_D))
cameraNode_->Translate(Vector3::RIGHT * MOVE_SPEED * deltaTime);
}
/// Scene.
SharedPtr<Scene> scene_;
/// Camera scene node.
SharedPtr<Node> cameraNode_;
float yaw_;
float pitch_;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment