how to implement Quake's movement in ue5 c++ pawn?
Assistant
Implementing Quake-style movement in Unreal Engine 5 (UE5) using C++ involves modifying a Pawn class to handle fast-paced, physics-based, first-person movement mechanics similar to those found in the Quake series. The core elements of Quake's movement include strafe-jumping, bunny hopping, and more responsive air control, each providing a slick, fast-paced gaming experience.
Here’s a step-by-step guide to implementing a basic version of Quake-like movement in UE5 using C++:
Step 1: Create a New C++ Pawn Class
Start by creating a new Pawn class that will handle the custom movement logic. In Unreal Editor, go to "File" → "New C++ Class", then choose Pawn as the parent class and name it, for example, MyQuakePawn.
Step 2: Customize Pawn Properties
Open the newly created C++ class and include necessary headers and properties.
Make sure to configure movement input bindings in either the engine's Input settings or through code.
Step 3: Extend Movement Mechanics
To fully realize Quake-like movement, the relevant physics need to be set up. This typically involves:
Enhancing Air Control: Allow sharp turns during jumps.
Implementing Strafe Jumping: Modify velocity based on the jump angle and current speed.
Adding Bunny Hopping: Facilitate repeated jumps maintaining or increasing speed.
Implement these features by further integrating and adjusting physics calculations within the Tick method, possibly extending into separate methods or components for clarity and reusability.
Step 4: Test and Tune
Compile your code, create a pawn instance in the game world, and test the movement. Tuning involves adjusting velocities, physics parameters, and input responsiveness until the desired behavior is achieved.
Final Thoughts
This guide provides a foundational framework. For production-level complexities like robust collision handling, advanced physics states, or multiplayer synchronization, deeper engine integrations and optimizations are required. Explore Unreal Engine's documentation and community forums for additional insights and optimizations.
User
using this code my character keeps moving on its own without pressing keys
Assistant
To correct the issue where your character continuously moves without any user input, you should adjust how you handle the CurrentVelocity in both your Tick method and the movement functions. The issue might be that CurrentVelocity is not being properly reset or updated according to the input values.
1. Reset CurrentVelocity Each Tick
Instead of updating CurrentVelocity directly in the movement functions (MoveForward, MoveRight), it might be more effective to calculate the velocity each frame based on the current input. This ensures that movement stops when no keys are pressed.
Here’s how you can update your class to handle this:
Update Tick Function:
Adjust the Tick method so that it only applies the velocity if there is active player input:
cpp
void AMyQuakePawn::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
// Reset current velocity
CurrentVelocity = FVector::ZeroVector;
// Update velocity based on input
UpdateMovement(DeltaTime);
// Apply movement
if (!CurrentVelocity.IsNearlyZero())
{
FVector NewLocation = GetActorLocation() + (CurrentVelocity * DeltaTime);
SetActorLocation(NewLocation);
}
}
Implement Input Handling:
Create a method that processes the player's movement input and calculates the current velocity accordingly:
Note: You may need to ensure the InputComponent is properly initialized before using it like this, or alternatively, maintain state variables for input values that are updated in and .
User
what if I'm using the new enhanced input system UEnhancedInputComponent?
Assistant
If you are using the new Enhanced Input System that was introduced in Unreal Engine 5, which utilizes UEnhancedInputComponent rather than the traditional UInputComponent, you’ll need to adapt your approach a bit differently to handle input mapping and input triggers.
Here is how you can adjust your implementation using the Enhanced Input System:
1. Setup Enhanced Input Bindings
Assuming you've already installed and enabled the Enhanced Input plugin in your UE5 project, you'll start by defining input mappings in the project settings. This should include action and axis mappings for forward movement, right movement, and jumping.
Creating Action Mappings:
Go to Edit > Project Settings > Engine > Input.
Under ‘Input’ settings, switch to the ‘Enhanced Input’ section.
Add new Action and Axis mappings:
Action Mappings (e.g., "Jump")
Axis Mappings (e.g., "MoveForward", "MoveRight")
Assign appropriate keys and adjust properties as needed.
2. Update Pawn to Use UEnhancedInputComponent
Modify your code to use UEnhancedInputComponent instead of UInputComponent. This involves changes primarily in your setup input method and the bindings themselves.
give me the entire implementation given that this is my function:
void AXpCollectorPawn::SetupPlayerInputComponent(
UInputComponent* PlayerInputComponent) {
Super::SetupPlayerInputComponent(PlayerInputComponent);
if (auto* eic = CastChecked(PlayerInputComponent)) {
eic->BindAction(move_fb_action,
ETriggerEvent::Triggered,
this,
&AXpCollectorPawn::move_fb);
Let's construct the entire implementation of your AXpCollectorPawn class to include the Quake-like movement mechanics, using the setup you've specified with the UEnhancedInputComponent. I will provide you with the class header and source definitions, which includes input handling, movement updates, and jump controls using the Enhanced Input System.
A. Class Header File (AXpCollectorPawn.h)
cpp
#pragma once
#include "CoreMinimal.h"
#include "GameFramework/Pawn.h"
#include "Camera/CameraComponent.h"
#include "EnhancedInputComponent.h"
#include "InputAction.h"
#include "AXpCollectorPawn.generated.h"
/**
* Represents a pawn similar to Quake's style of movement.
*/
UCLASS()
class YOURGAME_API AXpCollectorPawn : public APawn
{
GENERATED_BODY()
public:
AXpCollectorPawn();
// Velocity for applied movement
FVector CurrentVelocity;
bool bIsJumping;
protected:
virtual void BeginPlay() override;
virtual void Tick(float DeltaTime) override;
virtual void SetupPlayerInputComponent(UInputComponent* PlayerInputComponent) override;
// Input actions
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Input")
UInputAction* MoveForwardBackwardAction;
UPROPERTY(EditAnywhere, BlueprintReadOnly, Category = "Input")
UInputAction* MoveLeftRightAction;
// Movement handlers
void MoveForwardBackward(const FInputActionValue& Value);
void MoveLeftRight(const FInputActionValue& Value);
// Camera component
UPROPERTY(VisibleAnywhere, BlueprintReadOnly, Category = "Camera")
UCameraComponent* CameraComponent;
private:
void StartJump();
void StopJump();
};
B. Source File (AXpCollectorPawn.cpp)
cpp
User
why there is only moveRight?
Assistant
In the example provided, a conceptual mistake was made where the right-left movement handling was named ambiguously. As detailed, there should be handlers for both forward-backward and left-right movements. However, in the SetupPlayerInputComponent within the .cpp file, there should be correct binding methods that handle both types of movement (forward-backward and left-right) not just left-right movement.
To clarify and ensure the input bindings are set up correctly for both moving forward-backward and moving left-right, I will correct and provide a detailed explanation on the input handling. Here is the corrected approach:
Header File (AXpCollectorPawn.h)
Keep this file as given before, ensuring you have two UInputAction* for forward-backward and left-right movements.
Corrected Source File (AXpCollectorPawn.cpp)
Here's the corrected version demonstrating how each axis should be handled separately:
cpp
#include "AXpCollectorPawn.h"
AXpCollectorPawn::AXpCollectorPawn()
{
PrimaryActorTick.bCanEverTick = true;
// Initialize the CameraComponent
CameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComponent"));
RootComponent = CameraComponent;
}
void AXpCollectorPawn::BeginPlay()
{
Super::BeginPlay();
}
void AXpCollectorPawn::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
// Apply the current velocity to move the pawn.
if (!CurrentVelocity.IsNearlyZero())
{
FVector NewLocation = GetActorLocation() + (CurrentVelocity * DeltaTime);
SetActorLocation(NewLocation);
}
}
void AXpCollectorPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
if (auto* EIC = Cast<UEnhancedInputComponent>(PlayerInputComponent))
{
EIC->BindAction(MoveForwardBackwardAction, ETriggerEvent::Triggered, this, &AXpCollectorPawn::MoveForwardBackward);
EIC->BindAction(MoveLeftRightAction, ETriggerEvent::Triggered, this, &AXpCollectorPawn::MoveLeftRight);
}
}
void AXpCollectorPawn::MoveForwardBackward(const FInputActionValue& Value)
{
// Get the float value from the input action and manipulate it for movement speed.
CurrentVelocity.X = Value.Get<float>() * 100.0f; // Speed modifier should be adjusted as needed
}
void AXpCollectorPawn::MoveLeftRight(const FInputActionValue& Value)
{
// Get the float value from the input action and manipulate it for movement speed.
CurrentVelocity.Y = Value.Get<float>() * 100.0f; // Speed modifier should be adjusted as needed
}
void AXpCollectorPawn::StartJump()
{
// Implement Jump logic here.
bIsJumping = true;
}
void AXpCollectorPawn::StopJump()
{
// Implement logic to stop jumping here.
bIsJumping = false;
}
User
this code worked, but the pawn keeps moving afterwards on its own without input?
Assistant
The issue where your pawn continues to move without ongoing input typically arises from how the current velocity is managed in your tick function. Specifically, if the CurrentVelocity isn't properly reset or adjusted when there is no input, it retains its last non-zero value, causing continuous movement.
To rectify this, you need to ensure your pawn's velocity is updated every frame based directly on user input—that is, continuously recalculated and set to zero if there is no input. Here is how to adjust your Tick method and input handling for this purpose:
Step 1: Update CurrentVelocity Each Frame Based on Input
Adjust the Tick function to dynamically set CurrentVelocity based on current input values each frame, ensuring that movement stops when inputs cease.
cpp
void AXpCollectorPawn::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
// Calculate fresh velocity from input each frame
FVector NewVelocity(0.f);
if (MoveInput.X != 0.f)
{
NewVelocity.X = MoveInput.X * 100.f; // Horizontal movement
}
if (MoveInput.Y != 0.f)
{
NewVelocity.Y = MoveInput.Y * 100.f; // Vertical movement
}
// Apply the current velocity to move the pawn
if (!NewVelocity.IsNearlyZero())
{
FVector NewLocation = GetActorLocation() + (NewVelocity * DeltaTime);
SetActorLocation(NewLocation);
}
// Reset CurrentVelocity after applying movement
CurrentVelocity = NewVelocity;
}
Step 2: Modify Input Handling Methods
Make sure your input handlers immediately update a member variable (MoveInput in this case) that is used by the Tick method to calculate the current frame velocity.
cpp
void AXpCollectorPawn::MoveForwardBackward(const FInputActionValue& Value)
{
MoveInput.X = Value.Get<float>(); // Directly store the input value
}
void AXpCollectorPawn::MoveLeftRight(const FInputActionValue& Value)
{
MoveInput.Y = Value.Get<float>(); // Directly store the input value
}
User
is this accurate?
Assistant
The general approach and recommendation I provided for updating the velocity each frame based on input is accurate and standard for addressing continual movement issues in games. However, the actual implementation might vary slightly depending on your specific project setup, or additional details of Unreal Engine's behavior that aren't taken into account in the given snippets.
Here’s a recap and some points to ensure the implementation works as expected:
Adjusting Tick Method
In the Tick method, the pivotal concept is recalculating the pawn's velocity each frame based on the current input vector, MoveInput, which should accurately reflect user input for that frame:
cpp
void AXpCollectorPawn::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
// Calculate velocity directly from input vector scaled by some factor for speed.
CurrentVelocity.X = MoveInput.X * 100.f; // Scale for forward/backward movement
CurrentVelocity.Y = MoveInput.Y * 100.f; // Scale for side-to-side movement
// Apply the calculated velocity to move the pawn
if (!CurrentVelocity.IsNearlyZero()) // Ensures there is significant movement to apply
{
FVector NewLocation = GetActorLocation() + (CurrentVelocity * DeltaTime);
SetActorLocation(NewLocation);
}
// Optionally reset MoveInput if continuous input is not desired
// MoveInput = FVector::ZeroVector;
}
Ensuring MoveInput Is Updated Correctly
The main issue could stem from how input states are recorded. If MoveInput does not get updated properly when no keys are pressed (i.e., to zero), the pawn will continue to use the last non-zero input. The methods handling the input should resemble:
cpp
User
problem fixed. Now i want my pawn to move faster
Assistant
To make your pawn move faster in Unreal Engine, you essentially need to adjust the parameters that control movement speed. Here are a few direct methods to increase the speed of your pawn based on your existing implementation:
1. Increase the Speed Multiplier
In the Tick method, the movement velocity is calculated by multiplying the MoveInput vector by a speed multiplier. You can increase this multiplier to make the pawn move faster.
In your existing code snippet, you might have a line that looks like this:
cpp
CurrentVelocity.X = MoveInput.X * 100.f; // Increase this value
CurrentVelocity.Y = MoveInput.Y * 100.f; // Increase this value
You can simply increase these multiplication factors to something higher to increase the speed. For instance:
Choose a value that matches the game play feel that you’re aiming for.
2. Use a Configurable Speed Variable
To have more control and flexibility over the setting (and potentially to allow players or other systems to modify the move speed dynamically), you can manage this value using a variable.
First, define a new public float variable in your pawn class header file:
cpp
public:
UPROPERTY(EditAnywhere, BlueprintReadWrite, Category = "Movement")
float MoveSpeedMultiplier = 300.f; // default to 300, adjust as needed
That's great to hear! I'm glad everything is working as you wanted. If you have more questions in the future, whether they're about further enhancing your project, exploring new Unreal Engine features, or anything else, don't hesitate to reach out. Happy developing, and I wish you the best of luck with your project!
User
here is my XpCollectorPawn.h code:
// Fill out your copyright notice in the Description page of Project Settings.
It looks like you've provided a solid structure for your AXpCollectorPawn class in Unreal Engine using the Enhanced Input system. This setup will allow you to handle input flexibly and manage the pawn movements effectively. Here’s a bit of a review and some tips on your code:
Key Components and Their Configuration
Input Actions and Mapping Context:
UInputAction* move_fb_action; and UInputAction* move_lr_action;: These are used for forward-backward and left-right movement bindings respectively.
UInputMappingContext* mapping_context;: This stores your input mappings which could encompass multiple actions.
Mesh and Camera:
UStaticMeshComponent* player_mesh;: Your ship, character, or the avatar's mesh.
UCameraComponent* player_camera;: The camera that follows or is attached to the pawn, providing the player's viewpoint.
Movement Handling:
FVector move_input;: This vector stores the current input from move_fb and move_lr actions.
FVector current_velocity;: Used to calculate and update the pawn’s position each frame based on the input.
Jump Handling:
bool is_jumping;: A flag to determine whether the pawn is currently in the middle of a jump.
Some Improvements/Tips
Initialize Defaults in Constructor: Ensure all your components, especially your mesh and camera, are properly initialized in the pawn’s constructor (AXpCollectorPawn()). Here's an example to initialize the camera and mesh:
cpp
AXpCollectorPawn::AXpCollectorPawn() {
// Create and configure the static mesh component
player_mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("PlayerMesh"));
RootComponent = player_mesh;
// Create and configure the camera component
player_camera = CreateDefaultSubobject<UCameraComponent>(TEXT("PlayerCamera"));
player_camera->SetupAttachment(RootComponent);
player_camera->SetRelativeLocation(FVector(-300.0f, 0.0f, 300.0f)); // Example offset
player_camera->SetRelativeRotation(FRotator(-45.0f, 0.0f, 0.0f)); // Example angle
// Enable the pawn to call Tick() every frame
PrimaryActorTick.bCanEverTick = true;
}
User
here is my cpp file:
// Fill out your copyright notice in the Description page of Project Settings.
AXpCollectorPawn::AXpCollectorPawn() {
// Set this pawn to call Tick() every frame.
// You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
// Called to bind functionality to input
void AXpCollectorPawn::SetupPlayerInputComponent(
UInputComponent* PlayerInputComponent) {
Super::SetupPlayerInputComponent(PlayerInputComponent);
if (auto* eic = CastChecked(PlayerInputComponent)) {
eic->BindAction(move_fb_action,
ETriggerEvent::Triggered,
this,
&AXpCollectorPawn::move_fb);
Your C++ class implementation for AXpCollectorPawn generally looks sound, with the combination of necessary components and the use of the Enhanced Input system in Unreal Engine 5. Here are a few points for review and potential improvements:
1. Velocity Update Mistake in Tick Function
You currently have a bug in your Tick method where you're adding current_velocity to the pawn's location instead of NewVelocity. This is a subtle error that affects movement behavior, especially right after input changes.
Update the Tick method as follows:
cpp
// Called every frame
void AXpCollectorPawn::Tick(float DeltaTime) {
Super::Tick(DeltaTime);
FVector NewVelocity(0.f);
if (move_input.X != 0.f) {
NewVelocity.X = move_input.X * 1000.f; // Adjust multiplier as necessary
}
if (move_input.Y != 0.f) {
NewVelocity.Y = move_input.Y * 1000.f; // Adjust multiplier as necessary
}
if (!NewVelocity.IsNearlyZero()) {
SetActorLocation(GetActorLocation() + NewVelocity * DeltaTime);
}
current_velocity = NewVelocity;
move_input = FVector::ZeroVector; // This reset is okay if input is frame-based
}
2. Input Binding in SetupPlayerInputComponent
The input binding code is correctly leveraging CastChecked to ensure the input component can be safely cast to UEnhancedInputComponent. Also, the usage of Triggered event type for continuous movement actions is appropriate. Ensure your MoveForwardBackwardAction and MoveLeftRightAction are correctly configured in UE Editor.
3. Logging
Logging in move_fb and move_lr is a great way for debugging. Consider changing the log level or message based on the input value for more contextual logging, which can aid in fine-tuning input responses:
cpp
User
is this Quake's movement?
Assistant
The C++ class implementation previously discussed does provide foundational movement controls such as moving forward, backward, left, and right, along with a basic setup for jumping. It leverages the Enhanced Input system in Unreal Engine to handle inputs more efficiently and with greater flexibility. However, it does not fully capture the highly dynamic and physics-based movement mechanics that are well-known in Quake-style gameplay, such as strafe jumping, bunny hopping, and advanced air control.
Here’s a brief overview of key characteristics in Quake’s movement system and what might be needed to replicate them:
1. Strafe Jumping
Strategic maneuver that allows players to jump and gain speed by rapidly alternating or combining movement keys in the air. Implementation often requires simulation of physics properties such as air control and momentum preserving.
2. Bunny Hopping
Allows players to maintain and gradually increase their speed by jumping repeatedly in specific timings and directions. Implementing bunny hopping involves custom handling of ground checks and jump velocity adjustments.
3. Air Control
Highly nuanced control while in the air, enabling players to steer significantly during jumps or falls. This aspect typically involves modifying how directional input affects velocity when off the ground.
4. Ramp Jumping or Surfing
Involves using angled surfaces to perform elevation jumps or accelerate using friction theories.
Steps to Mimic Quake’s Movement in Unreal Engine:
a. Implement Advanced Input Handling
You already have an Enhanced Input setup, which is excellent. This should be extended to handle complex combinations and sequences of inputs and their impact on movement physics.
b. Tweak Physics Properties
Overriding Unreal’s default physics to allow more fine-tuned control over acceleration, friction, and air control. Unreal Physics Material and custom Pawn movement handling will play a critical role here.
c. Customize Movement Code
Develop a custom movement component or heavily modify the existing pawn movement logic to incorporate the dynamics such as strafe and bunny hopping patterns:
cpp
virtual void Tick(float DeltaTime) override
{
Super::Tick(DeltaTime);
// Handle horizontal movement including strafe logic
// Handle vertical movement including bunny hopping logic
// Apply advanced air control
}
User
i noticed when i move in diagonal direction my speed increases, why?
Assistant
The increase in speed when moving diagonally is typically due to a common vector addition issue in many movement systems. When you handle input for moving forward/backward and left/right independently without normalization, moving diagonally results in combining two vectors, generally leading to a longer resultant vector than moving in a single direction.
Understanding the Vector Calculation
Suppose:
Moving straight (forward or sideways) assigns a velocity of 100 units/s.
When moving diagonally (forward and right, for example), the vector components from each direction are added:
The resultant diagonal vector magnitude (using Pythagoras' theorem) is:
[ \sqrt{100^2 + 100^2} = \sqrt{20000} \approx 141.4 , \text{units/s} ]
This is approximately 1.414 times the speed of moving in a single direction, which is a 41% speed increase.
Solution: Normalize the Movement Vector
To counteract this issue and ensure that the player's maximum speed is consistent in all directions, the movement vector should be normalized if the player is inputting movement in more than one direction simultaneously. Here’s how you can modify your Tick function to incorporate normalization:
cpp
void AXpCollectorPawn::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
FVector NewVelocity(0.f);
if (move_input.X != 0.f) {
NewVelocity.X = move_input.X * 1000.f; // Speed factor for demonstration
}
if (move_input.Y != 0.f) {
NewVelocity.Y = move_input.Y * 1000.f; // Speed factor for demonstration
}
// Normalize the velocity if moving diagonally (i.e., input on both axes)
if (!FMath::IsNearlyZero(NewVelocity.Size()) && move_input.Size() > 1.0f) {
NewVelocity = NewVelocity.GetSafeNormal() * 1000.f; // Maintaining the same speed in all directions
}
if (!NewVelocity.IsNearlyZero()) {
SetActorLocation(GetActorLocation() + NewVelocity * DeltaTime);
}
current_velocity = NewVelocity;
move_input = FVector::ZeroVector;
}
User
FIXED
Assistant
Fantastic! I'm glad to hear that normalizing the movement vector resolved the issue with the increased speed when moving diagonally. This should provide a more consistent and expected movement behavior for your game, which is crucial for player experience especially in fast-paced or precision-required gameplay.
If you have any more questions, need further optimizations, or want to delve into other aspects of game development or Unreal Engine 5 features, feel free to ask. Good luck with your project, and happy coding!
User
this movement implementation is fps (frames/second) relative right?
Assistant
Yes, the movement implementation you're working with in Unreal Engine, as you've described and adjusted it, is FPS (frames per second) relative. This means that the distance your pawn moves is calculated based on frame updates, which inherently ties it to the frame rate at which the game is running. Using the time delta (DeltaTime) in your movement calculations correctly accounts for variations in frame rate, making the actual movement speed consistent across different frame rates.
Why Use DeltaTime
The variable DeltaTime represents the amount of time in seconds that passes between each frame. Multiplying your velocity by DeltaTime ensures that your movement speed is consistent regardless of variations in the frame rate. Here's how it works conceptually:
If your game runs at 60 FPS, then DeltaTime approximates to about ( \frac{1}{60} ) seconds (i.e., approximately 0.01667 seconds per frame).
If your game suddenly runs at 30 FPS due to performance issues, DeltaTime would be ( \frac{1}{30} ) seconds (i.e., 0.03333 seconds).
By using DeltaTime:
Even if the frame rate drops (thus increasing DeltaTime), the pawn moves a proportionally greater distance per frame to compensate, leading to consistent movement speed perceptually.
Example Calculation
Assume a desired constant velocity of 100 units per second:
At 60 FPS, with each frame, movement = ( 100 \times \frac{1}{60} = 1.67 ) units.
At 30 FPS, movement per frame becomes ( 100 \times \frac{1}{30} = 3.33 ) units.
Thus, despite the frame rate halving, the pawn still moves 100 units each second. This avoids variations in movement distance caused by frame rate fluctuations, which are especially common in different hardware setups or graphically intense scenes.
Ensuring Smooth Gameplay Across Varied Hardware
To ensure gameplay feels the same, regardless of hardware capability and consequent frame rate:
Always use DeltaTime for time-based calculations in game logic, particularly for movement, animations, and physics updates.
Important Considerations
Frame Rate Independence: While using DeltaTime makes physics and movements frame rate independent, remember that extremely low frame rates can still affect gameplay 'feel' and response times to inputs. Always aim to optimize performance and consider frame-pacing options if necessary.
Testing Under Different Frame Rates: It's beneficial to test your game under various frame rates to ensure consistent behavior. Unreal Engine allows you to simulate different frame rates in the editor for this purpose.
User
what about high fps?
Assistant
Addressing high frame rates involves similar considerations as managing low frame rates but with different impacts and sometimes challenges. In the context of games, particularly those developed with Unreal Engine, ensuring that gameplay is consistent across both low and high frame rates is crucial for providing a fair and uniform experience to all players.
Implications of High FPS:
Increased Responsiveness and Smoothness:
Higher frame rates can make the game feel smoother and more responsive. This is particularly beneficial in fast-paced action games where timing and precision are important.
Physics and Game Logic Bugs:
Some game physics or logic might behave unexpectedly at very high frame rates. For example, collisions might be missed if objects move too much between frames, or tightly timed sequences might fail because the time delta is too small.
Hardware Stress:
Unrestricted frame rates can cause unnecessary load on the GPU and CPU as they try to render and compute as fast as possible. This can lead to increased power consumption, heat, and potentially decrease hardware lifespan or trigger thermal throttling.
Managing High FPS:
1. Delta Time Relevance:
The use of DeltaTime becomes even more critical at high frame rates. Since DeltaTime represents the time between current and last frame, a higher frame rate will produce a smaller DeltaTime value, resulting in smaller movement increments per frame to maintain a consistent speed per second.
2. Frame Rate Capping:
One common approach to handle very high frame rates is to cap the frame rate. Unreal Engine allows you to set a maximum frame rate. This can be done via Blueprints or C++ code:
As with low FPS testing, ensure you test your game at high frame rates to observe any unexpected behaviors or performance issues.
4. Using Fixed Time Steps for Physics Calculations:
For more predictable physics, you may choose to update physics using a fixed time step. Unreal's physics engine, by default, tries to use fixed time steps (handled internally), but additional tuning and settings checks might be necessary to ensure consistency, especially under variable high frame rates.
User
how high fps affects my game impl?
Assistant
High frame rates can impact game implementations in several ways. The effects can be both positive, in terms of improved gameplay experience, and potentially negative, especially if the game logic is not adequately prepared to handle higher than expected FPS. Here’s a more detailed look:
Positive Impacts of High FPS:
Improved Smoothness and Responsiveness:
Higher FPS can make the game appear smoother to the eye and make it feel more responsive to player inputs. This is particularly noticeable in fast-paced games where precision and reaction time are crucial.
Enhanced Visuals:
With more frames rendered per second, animations and transitions look smoother, contributing to an overall improved visual experience.
Reduced Input Latency:
Higher FPS can reduce the input latency, i.e., the delay between a player’s action and its visible effect on the screen, which is critical for competitive gaming scenarios.
Possible Challenges with High FPS:
Physics and Timing Bugs:
When a game runs at an excessively high FPS, it can lead to problems such as physics calculations acting unpredictably (e.g., objects passing through each other because collision checks miss them) or timing-based processes executing incorrectly.
Resource Consumption:
Running a game at very high FPS requires more CPU and GPU resources. This increased demand can lead to higher power consumption, increased heat generation, and potentially throttling on some systems, particularly if the cooling is inadequate.
Hardware Disparities:
Players with high-end hardware may experience the game very differently compared to those on lower-end systems. This can be a concern for competitive games where a higher FPS provides a gameplay advantage.
Handling High FPS in Game Implementation:
a. Cap the Frame Rate:
Limiting the FPS to a reasonable maximum can prevent some of the negative impacts while still providing a smooth experience. Unreal Engine allows developers to set a maximum frame rate either globally or on a per-user basis.
b. Use Delta Time for Movement and Animations:
As discussed previously, using Delta Time ensures that your game’s movement and timing logic are based on real time rather than frame count, which helps maintain consistent behavior regardless of the frame rate.
User
you saw my AXpCollectorPawn implementation, how does it hold in high fps scenarios ?
Assistant
Your implementation of AXpCollectorPawn in Unreal Engine might experience typical impacts in scenarios where the frame rate is very high or quite low, mainly because of how the physics calculations (particularly movement) are currently handled. Here's an assessment:
Evaluating AXpCollectorPawn Under High FPS
Use of Delta Time:
You’re correctly using DeltaTime to adjust movement based on the time that has elapsed since the last frame, which is fundamental to guarantee consistent movement speeds across varying frame rates. This helps ensure that the pawn's speed doesn't fluctuate with FPS variations.
Current Velocity is FPS-Independent:
Because you are recalculating the current_velocity each frame based on move_input, multiplied by a constant that doesn’t depend on frame rate, the core of your velocity calculation is safe from different FPS conditions.
Potential Issue with Input Handling:
You process inputs directly per frame (move_fb and move_lr) and then reset move_input. This approach is normally fine, but at extremely high frame rates, this may lead to super responsive inputs which might feel overly sensitive to players. Conversely, at low FPS, it might feel sluggish.
Normalization of Movements:
If you implemented normalization for diagonal movements as discussed in your updates, this would ensure no unnatural speed boosts when moving diagonally, which is essential for maintaining consistency at any FPS.
Considerations for Improvement:
While the existing setup already takes care of movement re-scaling based on DeltaTime which is great for many high and variable FPS scenarios, consider the following to further robustify handling across varying frame rates:
Input Smoothing:
At very high frame rates, inputs could be treated to a smoothing or averaging mechanism where the input over a few frames is averaged to avoid overly jittery responses. This can help the game feel more consistent.
Fixed Time Steps for Game Logic:
If using physics or other simulations that need to be extremely precise and consistent, consider implementing fixed time steps within the physics calculations while keeping rendering on a flexible timing.
User
so what is the difference (benefits) between my movement implementation and just increasing X or Y on actor's location like this:
auto location = GetActorLocation();
location.X += val.Get().X;
SetActorLocation(location);
Assistant
Your current movement implementation in AXpCollectorPawn using DeltaTime and handling input via adjusted velocity vectors provides several advantages over a simplistic approach, which directly modifies the actor’s location based on input values without considering frame timing. Let’s explore the differences and benefits:
1. Frame Rate Independence:
Your implementation uses DeltaTime to scale movement, making the pawn’s movement consistent regardless of the frame rate. This is crucial for gameplay consistency across various hardware capabilities where frame rates might differ significantly.
Example:
At 60 FPS, DeltaTime is about 0.01667 seconds.
At 30 FPS, DeltaTime is about 0.03333 seconds.
If you move by 100 units per second:
Your code effectively moves the pawn 100 * 0.01667 ≈ 1.67 units each frame at 60 FPS.
At 30 FPS, it’s 100 * 0.03333 ≈ 3.33 units each frame.
This means the actual speed in world units per second remains consistent. Conversely, directly manipulating the X or Y coordinates would make movement speed directly tied to frame rate, which can lead to vastly different gameplay experiences on different systems.
2. Input Scalability and Flexibility:
By processing inputs as velocity vectors and integrating over time (DeltaTime), your implementation allows for smoother and more controlled character movements. It also simplifies adjustments and tuning of the movement dynamics (like acceleration, deceleration, and different movement speeds) without changing the approach to handling input.
3. Physics and Collision Handling Compatibility:
Using Unreal Engine’s movement functions (or custom velocity-based movement handling) often integrates more naturally with the engine’s collision detection and physics simulation systems. By updating position based on velocity and time, you adhere to Unreal's physics loop, potentially reducing issues like tunneling (where fast-moving objects move through collisions without detection) or erratic behavior on physics interaction.
4. General Best Practices:
Managing movement via velocity and time deltas aligns with general best practices in game development, particularly for dynamic games where smooth motion and consistency across different systems are key. Developers have more control to apply various physics principles like inertia, momentum, and forces more realistically and understandably.
User
now i want to add rotation to my pawn so i can rotate using the mouse like in fps shooter games
Assistant
To achieve mouse-based rotation for a first-person shooter (FPS) setup in Unreal Engine, much like in classic FPS games, there are several key components you need to consider and implement. These include capturing mouse input for rotation, applying these rotations correctly to your pawn, and ensuring that your camera responds appropriately to these inputs.
Step 1: Setup Input Bindings
Before writing any code, you need to ensure that your input mappings are properly set up in the Unreal Engine Editor:
Open your project settings by going to Edit > Project Settings.
Under the Engine section, find Input.
Add new Axis Mappings for looking around:
LookUp: Bind this to Mouse Y.
Turn: Bind this to Mouse X.
You may want to invert the Y-axis depending on your preference by using a negative scale value.
Step 2: Update Your Pawn's Header File
In your AXpCollectorPawn.h, add function declarations for handling these new input actions:
In your AXpCollectorPawn.cpp, implement the LookUp and Turn methods. This will apply the mouse movements to the pawn's rotation.
cpp
void AXpCollectorPawn::LookUp(float Value)
{
// Adjust the pitch, which affects how far up or down the camera points.
// Multiplies Value by a rotation speed factor and deltaTime to ensure smooth frame rate-independent rotation.
float RotationSpeed = 10.0f; // Adjust to taste
AddControllerPitchInput(Value * RotationSpeed * GetWorld()->GetDeltaSeconds());
}
void AXpCollectorPawn::Turn(float Value)
{
// Adjust the yaw, which affects horizontal rotation.
float RotationSpeed = 10.0f; // Adjust to taste
AddControllerYawInput(Value * RotationSpeed * GetWorld()->GetDeltaSeconds());
}
User
is it possible to not to use AddControllerPitchInput?
Assistant
Yes, it's certainly possible to implement rotation in your pawn without using AddControllerPitchInput and AddControllerYawInput, which are typically tied to the pawn's controller. Such methods are commonly used for simplicity and integration with Unreal's player controller system, but you can directly manipulate rotation by updating the pawn's rotation properties if a more direct control or specific behavior is required.
Directly Modifying Actor Rotation
You can instead directly adjust the rotation of your pawn using SetActorRotation, manipulating the rotation based on the input and considering frame time. Here’s how you can adjust both pitch and yaw manually:
Step 1: Add Rotation Properties
First, add properties to your pawn class to store the current yaw and pitch. Update AXpCollectorPawn.h to include these properties:
In your AXpCollectorPawn.cpp, you can directly manipulate these properties based on the input. Here’s an example implementation considering clamping to prevent extreme look up/down behavior (pitch):
cpp
void AXpCollectorPawn::LookUp(float Value)
{
float RotationSpeed = 10.0f; // Sensitivity of pitch movement
CurrentPitch += Value * RotationSpeed * GetWorld()->GetDeltaSeconds();
CurrentPitch = FMath::Clamp(CurrentPitch, MinPitch, MaxPitch); // Clamp to avoid flipping
// Apply rotation to the pawn
FRotator NewRotation = GetActorRotation();
NewRotation.Pitch = CurrentPitch;
SetActorRotation(NewRotation);
}
void AXpCollectorPawn::Turn(float Value)
{
float RotationSpeed = 10.0f; // Sensitivity of yaw movement
CurrentYaw += Value * RotationSpeed * GetWorld()->GetDeltaSeconds();
// Apply rotation to the pawn
FRotator NewRotation = GetActorRotation();
NewRotation.Yaw = CurrentYaw;
SetActorRotation(NewRotation);
}
User
according to the best practices, which method is most recommended?
Assistant
Both using AddControllerPitchInput/AddControllerYawInput and direct manipulation of actor rotation via SetActorRotation have their appropriate use cases and advantages, but the best practice typically depends on the specific requirements of your project, game type, and desired control granularity. Here’s a breakdown to help you decide:
Using AddControllerPitchInput and AddControllerYawInput:
Recommended for:
Games that rely heavily on Unreal Engine’s built-in Player Controller mechanics, which are designed to integrate seamlessly with other subsystems like camera controls, character movement, multiplayer support, and input management.
Projects that benefit from Unreal's handling of input smoothing, dead zones, and standardized behavior across different platforms.
Developers aiming for consistency with Unreal conventions, easing maintenance, and integration with other parts of the engine.
Advantages:
Ease of Use: These methods are straightforward to implement and require less code to handle rotation properly.
Integrated Features: Takes full advantage of Unreal's handling of various input concerns, including smooth rotation interpolation, replication in network games, and adherence to the settings configured in the Unreal Editor input system.
Flexibility: Easy to extend with Unreal’s features like input modifiers and exponential curves directly in project settings.
Directly Setting Actor Rotation (SetActorRotation):
Recommended for:
Custom simulations or applications where you need precise control over rotation logic that deviates significantly from standard gameplay mechanics.
Projects where player input might affect objects other than characters controlled by a Player Controller, such as freely rotating cameras, objects in simulations, or custom devices in VR environments.
Games requiring special rotation effects or precise programmatic control (like snapping angles, quick look functions, complex constraints beyond simple clamping).
Advantages:
Precision Control: Grants full control over how rotations are handled, processed, and applied, including complex mathematical manipulations if needed.
Custom Constraints: Allows for implementing custom constraints and behaviors like locking axes under specific conditions, custom smoothing algorithms, or non-linear rotation transitions.
Best Practices Recommendation:
User
with your first implementation, the pawn doesn't change direction when the turning. can you fix that?
Assistant
If you're finding that the pawn doesn't visually change direction (i.e., the mesh or camera does not rotate) when turning using the controller inputs (AddControllerPitchInput and AddControllerYawInput), it's likely that the pawn's settings regarding rotation are not configured to correctly respond to the controller's changes. This is a common issue especially if you are dealing with a custom pawn class where the default properties might not align with typical first-person or third-person character setups.
Here’s how you can adjust the configuration to ensure that the pawn reacts to the controller's rotation input:
Step 1: Review Pawn Settings
In the constructor of your pawn class (AXpCollectorPawn::AXpCollectorPawn()), you need to make sure that the pawn uses controller rotation for yaw (turning left/right). Depending on your specific setup and which part of the pawn you want to rotate (just the camera or the entire pawn), you may need to enable or disable certain properties:
cpp
AXpCollectorPawn::AXpCollectorPawn()
{
// Setup the pawn to use the controller's yaw, which affects horizontal rotation.
bUseControllerRotationYaw = true;
// Typically for a FPS, you don’t want the pawn itself pitching up and down, only the camera,
// so you might set:
bUseControllerRotationPitch = false;
// If the camera should follow the controller independently of the pawn rotation:
if (player_camera)
{
player_camera->bUsePawnControlRotation = true; // Camera uses the controller rotation
}
// Initialize other components....
}
Step 2: Ensure Consistent Controller Possession
Make sure your pawn is properly possessed by a controller, as controller inputs will not affect a pawn without a valid controller. This is especially significant in networked games or scenarios where the pawn might be dynamically spawned. Verify this in your spawning logic or game mode that the pawn is being possessed:
cpp
// In your Game Mode or wherever pawns are spawned and assigned to players
APlayerController* PlayerController = GetWorld()->GetFirstPlayerController();
if (PlayerController)
{
PlayerController->Possess(MySpawnedPawn);
}
User
is possible to fix the problem using GetActorForwardVector() and GetActorRightVector()?
Assistant
Yes, you can utilize GetActorForwardVector() and GetActorRightVector() to handle directional movement and rotation manually without relying on the built-in functions provided by the player controller. This approach gives you precise control over the movement and rotation logic, letting you manipulate the pawn’s direction and position based on its current orientation in the world.
Here’s how you can achieve movement and apply rotation manually using these vectors:
Adjusting Movement by Forward and Right Vectors
Assuming you already have a "Move Forward" and "Move Right" input setup, first ensure you capture the input effectively by using the axis values from the input. These vectors represent unit vectors in the direction the actor is currently facing, which makes them ideal for frame-independent directional movement.
1. Update Your Move Functions
Here’s how you could implement moving forward and sideways using GetActorForwardVector() and GetActorRightVector() in your actor's Tick method or in response to input:
cpp
void AXpCollectorPawn::MoveForward(float Value)
{
if (Value != 0.0f)
{
// Obtain the forward direction
FVector Direction = GetActorForwardVector();
// Update the Pawn's location
AddActorWorldOffset(Direction * Value * MovementSpeed * GetWorld()->GetDeltaSeconds(), true);
}
}
void AXpCollectorPawn::MoveRight(float Value)
{
if (Value != 0.0f)
{
// Obtain the right direction
FVector Direction = GetActorRightVector();
// Update the Pawn's location
AddActorWorldOffset(Direction * Value * MovementSpeed * GetWorld()->GetDeltaSeconds(), true);
}
}
2. Implementing Mouse-Look Rotation Manually
For rotating based on mouse input, you would handle the Turn and LookUp inputs manually:
cpp
User
I fixed it, this is the full code for cpp file, but i noticed that I can't move diagonal anymore, can you help ?
// Fill out your copyright notice in the Description page of Project Settings.
AXpCollectorPawn::AXpCollectorPawn() {
// Set this pawn to call Tick() every frame.
// You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
void AXpCollectorPawn::look_up(const FInputActionValue& val) {
// Adjust the pitch, which affects how far up or down the camera points.
// Multiplies Value by a rotation speed factor and deltaTime to ensure smooth
// frame rate-independent rotation.
AddControllerPitchInput(
val.Get() * RotationSpeed * GetWorld()->GetDeltaSeconds());
}
Assistant
From reviewing your provided code, it appears the issue with not being able to move diagonally arises because the move_input vector gets overwritten each time a new move input is triggered (either forward/backward or left/right). This means that if both a forward and a right input are triggered in the same frame, only the latter will affect the move_input due to the order of execution in Tick.
To handle diagonal movement appropriately, you need to combine the input vectors for both directions before applying them.
Adjusting the Input Handling
You should modify your move_fb and move_lr functions to add to the move_input vector instead of replacing it. This change allows simultaneous forward/backward and left/right inputs to be combined into a single movement vector, enabling diagonal movement.
cpp
void AXpCollectorPawn::move_fb(const FInputActionValue& val) {
UE_LOG(LogTemp, Warning, TEXT("move_fb triggered."));
// Combine the forward vector scaled by input value with the existing move input
move_input += GetActorForwardVector() * val.Get<float>();
}
void AXpCollectorPawn::move_lr(const FInputActionValue& val) {
UE_LOG(LogTemp, Warning, TEXT("move_lr triggered."));
// Combine the right vector scaled by input value with the existing move input
move_input += GetActorRightVector() * val.Get<float>();
}
Correct the Movement Application in Tick
Additionally, there’s an error in the way new_velocity is applied to set the actor location:
It looks like you're erroneously adding GetActorForwardVector() to the location directly, which doesn’t make much sense. It seems you might have intended to scale new_velocity (which should already include the direction) by DeltaTime. The correct application should simply add new_velocity * DeltaTime to the current location, assuming new_velocity has been properly calculated including both forward and right components through .
User
does the name move_input suits the variable or this is not really a move_input?
Assistant
The name move_input for a variable in your code captures the concept that it is derived from player input intended to control movement. However, its usage in the code goes beyond merely holding the raw input values; it represents an accumulated directional vector that influences the pawn's movement within the game world. This might make the name slightly misleading or less informative about its actual function.
Here are a few alternative naming suggestions that might give a clearer idea of the variable's purpose and how it is used:
movementVector: This name emphasizes that the variable represents a vector that defines the direction and intensity of movement. It clearly communicates that this is used to compute the whereabouts or future position of the pawn.
directionalInput: A name like this clearly indicates that the variable involves input from the user and that this input is directional.
combinedMovementDirection: This name is more descriptive, indicating that the variable represents a combination of movement directions (possibly including both horizontal and vertical movement vectors).
inputVelocity: This name implies that the variable not only stores directional input but also that this input is directly used to calculate a type of velocity for the pawn.
moveDirection: Simple and straightforward, this name communicates that the variable consolidates directional inputs into a single movement direction.
accumulatedMoveInput: This suggests that the variable accumulates or integrates multiple movement inputs over time or within a single frame, capturing both the nature of the input and its usage.
navigationVector: This slightly more abstract name suggests the variable is central to navigating or steering the pawn around the game environment.
Consideration for Refactoring
If you decide that a different name would better suit the variable based on its role in your code, ensure that you update all references to the variable across your codebase. This will maintain consistency and clarity, which is crucial for future maintenance or expansion of your code.
When naming variables, the key is to strike a balance between simplicity and expressiveness — making sure the name is both concise enough for easy use in code and descriptive enough to quickly convey its purpose without needing to look up its initial definition. In this case, opting for a name like or might provide a good balance, clearly reflecting the purpose of the variable in controlling the pawn's movement based on player input.
User
isn't it current velocity?
Assistant
Reviewing the usage of the variable move_input in the context of how it's being handled in your provided code, it appears to initially act more like a directional vector collected based on input values. However, in essence, it does represent a form of instantaneous or "current" velocity vector before being adjusted and applied to the pawn's position.
Here's a breakdown of how move_input is being used:
move_input accumulates movement directions from input methods like move_fb and move_lr. Each call to these methods adjusts move_input based on player actions, scaling these directional vectors by the input values.
Inside the Tick method, move_input is normalized and scaled by a movement speed factor, and then used to update the actor's location, essentially serving as a velocity vector (direction and magnitude).
Given this operation, the name move_input might be a bit misleading if one considers the full lifecycle of the variable through a frame update. It starts as an input representation but quickly transforms into a velocity calculation for actual movement application. If the primary function in the game logic considers the transformation of this input into a tangible movement speed and direction, a name reflecting its role as a velocity vector might indeed be more apt and less confusing.
Recommendations:
currentVelocity: This would be a suitable rename, as it clearly denotes its role in holding the current frame's computed velocity based on the player's input. It reflects not just any internal state but specifically the velocity that will govern the pawn's movement.
inputVelocity: Another good option, mixing the origin of the vector with its function. This tells that the vector starts as input but is formulated as a velocity vector.
velocityFromInput: This name emphasizes that this velocity is directly derived from user inputs, which is precisely what happens in your game logic.
To proceed with renaming move_input to something like currentVelocity, you'd update its declarations and any usage throughout your code:
Change the variable definition in the header file and source file.
Update all places where move_input is modified or read, such as in move_fb, move_lr, and Tick.
This renaming could improve code readability and maintainability by making the variable’s role in movement computation clearer to other developers or when revisiting the code after some time. Overall, such direct and meaningful naming aligns better with best practices in software development, especially in complex systems like game development where clarity can significantly affect the ease of updating and debugging code.
User
can bhopping be implement if I use builtin PlayerController rotations like AddControllerYawInput...?
Assistant
Yes, bunny hopping (often abbreviated as "bhopping") can be implemented in the Unreal Engine even if you are using built-in player controller functions like AddControllerYawInput for rotation handling. Bhopping typically depends more on how you handle movement and jumping physics than how you manage looking or turning movements.
Bunny hopping is a movement mechanic that allows players to gain increased movement speed and momentum by jumping and strafing correctly as they hit the ground. Implementing this in Unreal Engine involves tweaking the pawn's movement logic, particularly how jumping and ground contact are handled, rather than directly affecting how rotation input is processed.
Key Components for Implementing Bunny Hopping:
Handling Jumping and Air Movement:
Override or extend the pawn's jumping mechanism to check if the player attempts to jump again right before hitting the ground (queueing the jump).
Implement logic to preserve or slightly increase horizontal velocity when the player jumps again immediately upon landing.
Advanced Input Handling for Movement:
Capture strafe input while in the air. Strafing while in mid-air is essential for bhopping as it allows players to control their direction and maintain speed.
Use AddMovementInput or similar functions to translate these strafe inputs correctly considering the player's current velocity and orientation.
Modifying Physics or Movement Properties:
Adjust the air control properties in your pawn's movement component to allow more control while airborne.
Tweak friction and gravity settings if necessary to support continuous momentum.
Example Implementation Sketch:
Here’s a basic conceptual outline of how you might start implementing bhopping in a pawn that uses the built-in controller for rotations:
cpp
User
when I look up, my pawn leaves the ground, why? can you help? I want it to be like any other fps shooter game, being able to look up without flying lol. My code:
// Fill out your copyright notice in the Description page of Project Settings.
AXpCollectorPawn::AXpCollectorPawn() {
// Set this pawn to call Tick() every frame.
// You can turn this off to improve performance if you don't need it.
PrimaryActorTick.bCanEverTick = true;
void AXpCollectorPawn::look_up(const FInputActionValue& val) {
// Adjust the pitch, which affects how far up or down the camera points.
// Multiplies Value by a rotation speed factor and deltaTime to ensure smooth
// frame rate-independent rotation.
AddControllerPitchInput(
val.Get() * RotationSpeed * GetWorld()->GetDeltaSeconds());
}
// Called to bind functionality to input
void AXpCollectorPawn::SetupPlayerInputComponent(
UInputComponent* PlayerInputComponent) {
Super::SetupPlayerInputComponent(PlayerInputComponent);
Assistant
It sounds like the issue you're facing—your pawn "leaving the ground" when looking up—could be linked to how the rotation and its consequences are managed in your pawn.
One common mistake could be misunderstanding or misusing bUseControllerRotationPitch. If this is set to true for a pawn generally designed to be on the ground (like in standard FPS games), it will cause the entire pawn (including its collision and movement components) to pitch up and down, not just the camera. This can give the effect that the entire pawn is tilting with respect to the ground. This behavior is typically not desired in traditional FPS settings, where only the camera's pitch should change (to look up and down) without affecting the pawn's orientation relative to the ground.
Solution
You should set bUseControllerRotationPitch to false for the pawn, and handle the pitch movement directly through the camera component, ensuring that only the camera orientation changes when looking up or down.
Here is a revised version of your AXpCollectorPawn constructor:
cpp
AXpCollectorPawn::AXpCollectorPawn() {
PrimaryActorTick.bCanEverTick = true;
player_mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("PlayerMesh"));
RootComponent = player_mesh;
player_camera = CreateDefaultSubobject<UCameraComponent>(TEXT("PlayerCamera"));
player_camera->SetupAttachment(RootComponent);
player_camera->bUsePawnControlRotation = true; // Let the camera alone follow controller rotation.
bUseControllerRotationYaw = true; // The Pawn should rotate around yaw to turn left or right.
bUseControllerRotationPitch = false; // The pawn itself should not pitch up and down.
bUseControllerRotationRoll = false; // Typically, you do not want roll changes in an FPS.
}
In this setup:
bUsePawnControlRotation: This setting on the Camera Component ensures that the camera rotates with the controller's pitch and yaw, but these rotations are isolated to camera adjustments and do not affect the pawn's 'physical' orientation concerning the world's horizontal plane.
User
After trying your solution, the pawn does not elevate but the camera look up/pitch is lock i can't move it up and down
Assistant
The issue you're experiencing where the camera pitch is locked and not allowing up or down movement, despite bUseControllerRotationPitch being set to false on the pawn, likely stems from how camera rotations are being handled within Unreal Engine's input system and the camera component's settings.
To address the issue, follow these steps to ensure the camera is allowed to look up and down properly:
Step 1: Enable Camera Control Rotation
First, check and update how the camera component is attached and its settings:
Ensure the Camera Uses Pawn Control Rotation: If bUsePawnControlRotation is set to true on your camera component, it should inherit the controller’s rotation. This setting allows the camera to automatically use the pitch, yaw, and roll values from the player controller.
SetupAttachment Call: Make sure the camera’s attachment to the pawn does not reset or inherently block its pitch rotation. Generally, it should be attached simply to allow physical connection without enforcing specific rotation constraints that might come from the parent component if other settings are amiss.
Here is a sketch of how your camera component should be set:
cpp
player_camera = CreateDefaultSubobject<UCameraComponent>(TEXT("PlayerCamera"));
player_camera->SetupAttachment(RootComponent);
player_camera->bUsePawnControlRotation = true; // Camera uses the controller's rotation, including pitch.
Step 2: Adjust Player Controller Settings
Since bUseControllerRotationPitch is set to false on your pawn, ensure that your camera component is still allowed to rotate along its local pitch axis, and the player controller should indeed be managing the pitch input properly.
cpp
// Check in your Pawn's or PlayerController's BeginPlay or initialization sections:
APlayerController* PC = Cast<APlayerController>(GetController());
if (PC)
{
PC->bUsePawnControlRotation = true; // The Controller should update its rotation from input.
}
Step 3: Verify Input Bindings
Ensure that your input for looking up and down is correctly binding and functioning within the method. The bindings should be calling a function that applies input to the controller’s pitch.
User
i get Cannot resolve symbol 'AddPitchInput' in lookup function
Assistant
Apologies for the confusion. The method AddPitchInput isn't defined as such in Unreal Engine's API; it was an oversight in the provided example. The correct method to modify the pitch through the player controller would be done using either AddPitchInput on the input component when bound directly, or through the AddControllerPitchInput method, which correctly modifies the pitch of the controller.
The AddControllerPitchInput method is part of the APlayerController class and adjusts the pitch of the character's view rotation based on the rules defined by Unreal Engine's controller system, including any settings related to view limits, inversion, and sensitivity that have been configured. This method handles pitch adjustments respecting any constraints or configurations for the player controller like pitch limits or control inversion.
Here is how you can correctly implement the pitch adjustment using AddControllerPitchInput:
Modified LookUp Function
Make sure your LookUp function uses AddControllerPitchInput to adjust the pitch rotation based on input. Here's how you can define it correctly:
cpp
void AXpCollectorPawn::LookUp(float Rate)
{
APlayerController* PC = Cast<APlayerController>(GetController());
if (PC && Rate != 0.0f)
{
// This directly adds pitch input handled by the player controller.
PC->AddControllerPitchInput(Rate);
}
}
Ensure Proper Player Control Settings
Also, ensure that your player controller is set up to use the player's control rotation for the camera. In your Pawn's constructor or initializer, you might need to set:
cpp
bUseControllerRotationYaw = true;
bUseControllerRotationPitch = true; // You need this enabled to control pitch on the controller directly.
bUseControllerRotationRoll = false; // Typically not needed in FPS games.
In your camera component:
cpp
player_camera->bUsePawnControlRotation = true;
Input Binding
Verify that the axis for looking up/down is bound correctly in your :
User
using bUseControllerRotationPitch = true; makes the pawn fly again, and even setting it to false locks the look up
Assistant
If setting bUseControllerRotationPitch = true on your pawn causes it to appear as if it's "flying" or moving vertically when you try to look up or down, and setting it to false locks up the vertical camera movement, you need to adjust how the camera's pitch rotation is handled independently from the pawn's physical rotation.
For FPS games, typically, you want the camera to rotate up and down (pitch) without affecting the pawn’s rotation on the pitch axis, but the pawn should rotate left and right (yaw) along with the camera, affecting horizontal orientation.
Here's a structured approach to separate the camera's pitch movement from the pawn's body rotation:
1. Configure Pawn Rotation
In your pawn’s constructor, set up the rotation properties correctly:
cpp
AXpCollectorPawn::AXpCollectorPawn() {
PrimaryActorTick.bCanEverTick = true;
player_mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("PlayerMesh"));
RootComponent = player_mesh;
player_camera = CreateDefaultSubobject<UCameraComponent>(TEXT("PlayerCamera"));
player_camera->SetupAttachment(RootComponent);
// Configuring pawn rotation settings
bUseControllerRotationPitch = false; // Ensure pawn does NOT rotate on the pitch axis.
bUseControllerRotationYaw = true; // Allow pawn to rotate on the yaw axis.
bUseControllerRotationRoll = false; // Ensure pawn does NOT rotate on the roll axis.
}
2. Configure Camera Rotation
Ensure that the camera component is set to use the controller's rotation:
cpp
player_camera->bUsePawnControlRotation = true; // This allows the camera to rotate independently according to controller input.
3. Handling Input for Looking Up and Down
You will manually add controller pitch input within your input handling function:
cpp
void AXpCollectorPawn::LookUp(float Value)
{
if (Controller && Value != 0.0f)
{
Controller->AddPitchInput(Value);
}
}
User
I solved the problem of the pawn leaving the ground by setting bUseControllerRotationYaw = true; bUseControllerRotationPitch = false; bUseControllerRotationRoll = false;
and the following code:
void AXpCollectorPawn::look_up(const FInputActionValue& val) {
UE_LOG(LogTemp, Warning, TEXT("look_up triggered."));
if (val.Get() != 0.f) {
//CAMERA ROTATION
FRotator _r = player_camera->GetRelativeTransform().GetRotation().Rotator();
// Adjust the pitch, which affects how far up or down the camera points.
// Multiplies Value by a rotation speed factor and deltaTime to ensure
// smooth frame rate-independent rotation.
_r.Pitch +=
-val.Get() * RotationSpeed * GetWorld()->GetDeltaSeconds();
player_camera->SetRelativeRotation(_r);
}
}
Assistant
Great to hear that you've managed to solve the problem of the pawn leaving the ground by adjusting the player controller's rotation settings and implementing custom rotation logic for the camera!
Your current implementation in the look_up function effectively handles pitch rotation by directly setting the camera's relative rotation. This grants you precise control over how the camera behaves when looking up and down, independent of the pawn's rotation settings. This sort of control is particularly beneficial in creating first-person shooter (FPS) mechanics where vertical aim should not affect the character's world orientation.
Here are a few considerations and potential enhancements for your current setup:
1. Clamping Rotation
To prevent the camera from rotating too far up or down (which can lead to disorienting views where the camera flips over), you might consider clamping the pitch value. This can prevent the camera from rotating beyond a realistic vertical limit.
Here, MinPitch and MaxPitch are constants that you would define according to how far up and down you want the player to be able to look. Commonly, -90 degrees for MinPitch and 90 degrees for MaxPitch are sufficient for full vertical movement without flipping, but you might adjust these based on the specific needs and feel of your game.
2. Handling Fast Frame Rate Changes
Your method uses GetDeltaSeconds(), which is good practice as it ensures smooth and frame rate-independent rotation. Just ensure that RotationSpeed is tuned to work well across a range of expected frame rates.
3. Debugging
The log statement is a nice addition for debugging. Once you confirm the functionality is stable and behaves as expected, remember to adjust the verbosity level or remove it to clean up your game's runtime logs.
4. Consider Input Sensitivity
The multiplication by -val.Get<float>() effectively inverts the typical mouse/controller Y-axis, which is common in many FPS games where the Y-axis is inverted by default. If you plan to provide options for players, you might want to make this behavior configurable via a settings menu that toggles pitch inversion.
5. Update General Settings
Finally, verify and potentially update any related settings in your game that concern input, camera control, and player ergonomics to match the behavior expected with your new camera control setup.
It sounds like your system is on a solid track for providing a smooth and intuitive FPS camera experience. Keep these considerations in mind as you continue to refine and test your implementation. You're doing a great job of tailoring the Unreal Engine's capabilities to fit the unique needs of your project.
User
_r.Pitch = FMath::Clamp(_r.Pitch, MinPitch, MaxPitch); had no effect on flipping, using a new object FRotator(_r.Pitch, 0, 0) fixed the flip for me
Assistant
Thank you for sharing your solution! It appears the issue was related to how rotations are applied and interpreted in Unreal Engine. Unreal Engine uses a left-handed coordinate system, where rotations can sometimes behave differently than expected due to cumulative angles and the way rotations are compounded.
When adjusting rotations, particularly with quaternions (which Unreal may use under the hood for rotation transformations to avoid issues like gimbal lock), direct manipulation of FRotator properties (like Pitch, Yaw, Roll) might lead to unexpected behaviors when the rotation moves beyond certain thresholds (such as the infamous gimbal lock or flip-over at extreme angles).
You effectively reset the accumulated rotations that might be causing issues. This approach ensures that the pitch is strictly defined with no unintentional influence from the other axes, thereby preventing the camera from flipping.
Implementation Notes:
Clamping Before Setting the Rotation:
Ensure the pitch is clamped before setting it to the rotation, which prevents even the assignment of out-of-bound values:
Replace MinPitch and MaxPitch with your angle limits, typical values might be -90 and 90 degrees respectively.
Consider Inverting Via Settings:
It's common to allow users to invert the Y-axis through gameplay settings, which you could implement by multiplying the pitch delta by either 1.0f or -1.0f based on a user setting.
Smoothness and Responsiveness:
Tuning RotationSpeed is crucial to ensuring the camera feels responsive yet smooth. Depending on your game's mechanics, you might want to offer sensitivity settings to the players.
User
FMath::Clamp(_r.Pitch, MinPitch, MaxPitch) didn't work in limiting the view angle
Assistant
If FMath::Clamp(_r.Pitch, MinPitch, MaxPitch) is not effectively clamping the angle as expected, it could be due to the order of operations or how the rotation is being applied. Here are some detailed steps and checks to ensure robust clamping of your camera's pitch angle:
1. Debugging Current Pitch Values
First, verify that the pitch values are being adjusted as expected before and after clamping. You can use logging to check the state of these values:
The FRotator constructor is sensitive to how arguments are passed. Ensuring you only adjust the pitch and keep other angles intact or controlled can prevent unwanted roll effects or axis flipping:
When applying rotational input, make sure to apply the delta effectively, considering Unreal's left-handed coordinate system which might sometimes make rotations appear inverted:
cpp
_r.Pitch += val.Get<float>() * RotationSpeed * GetWorld()->GetDeltaSeconds(); // Remove the negation if inversion is not needed
_r.Pitch = FMath::Clamp(_r.Pitch, MinPitch, MaxPitch);
FRotator NewRotation = FRotator(_r.Pitch, _r.Yaw, 0.0f);
player_camera->SetRelativeRotation(NewRotation);
User
"Avoiding Direct Manipulation of Rotators:" what do you suggest ?
Assistant
In Unreal Engine, direct manipulation of FRotator values can sometimes lead to unintended issues such as gimbal lock, unexpected rotations due to angle wrapping, or rotations beyond intended limits. This problem arises especially with the Pitch (up and down looking) in a first-person camera, where exceeding conventional bounds (e.g., looking too far up or down) can flip the camera.
To avoid problems associated with direct manipulation of rotators and maintain a robust and intuitive camera control system, consider the following approaches:
1. Use Built-in Functions for Rotation Adjustments
Unreal Engine provides a set of built-in functions designed to handle rotations more safely and intuitively:
AddControllerPitchInput() and AddControllerYawInput(): These remember previous states and handle potential gimbal lock or angle wrapping internally. Particularly for player characters or cameras, these methods ensure rotations are smooth and consistent with the game's other mechanics.
2. Limiting Pitch Range Properly
When handling pitch, especially for a first-person view, ensure the pitch range remains between your determined angles (e.g., -90 to +90 degrees). You can manage this either by manually clamping pitch values before setting them or by implementing checks wherever pitch values get updated.
Clamping at Input Collection Point: Before applying input to adjust the pitch, clamp the values:
For complex rotation logic, particularly where multiple rotations might be combined or heavily modified, consider using quaternions to manage transformations. Quaternions avoid gimbal lock and ensure a continuous range of rotation:
Convert Rotators to Quaternions When Performing Multiple Rotations or Adjustments
4. Setting Rotations via Transformation Functions
Rather than directly setting the Rotation values, use kinematic equations or transformation matrices that Unreal Engine supports to alter position and rotation:
User
AddControllerPitchInput() and AddControllerYawInput() are not camera related
Assistant
You are correct; AddControllerPitchInput() and AddControllerYawInput() are functions related to the player controller and effectively modify the controller's rotation, which is typically used to drive camera orientation in common character movement setups. However, they are indirectly related to camera behavior because they often control the rotational part of the camera in setups where the camera's bUsePawnControlRotation is enabled.
In setups typical to first-person and third-person games, the camera is attached to the character (or pawn), and its rotation is dictated by the player controller's yaw and pitch when bUsePawnControlRotation on the camera component is set to true. This causes the camera to follow the controller's orientation, thus making these controller functions relevant for camera behavior.
Proper Use of Controller Functions for FPS Camera Control
To solidify the understanding and ensure a robust FPS camera behavior, here’s how you can use these functions effectively within an Unreal Engine FPS setup:
1. Player Controller Configuration:
Ensure the player controller allows rotation input and controls the pawn’s orientation appropriately:
cpp
AXpCollectorPawn::AXpCollectorPawn()
{
// Configuration allowing direct yaw rotation from the controller which should affect both the pawn's orientation and camera in a typical FPS.
bUseControllerRotationYaw = true;
bUseControllerRotationPitch = false; // Prevents the pawn itself from tilting up and down.
bUseControllerRotationRoll = false; // Generally unused in FPS.
// Setup the camera
player_camera = CreateDefaultSubobject<UCameraComponent>(TEXT("PlayerCamera"));
player_camera->SetupAttachment(RootComponent);
player_camera->bUsePawnControlRotation = true; // Camera uses controller rotation.
}
2. Implementing Pitch and Yaw Input:
Using AddControllerYawInput and AddControllerPitchInput allows for smooth, frame rate-independent rotation handled by Unreal's input system, respecting game settings like sensitivity and inversion.
cpp
User
AddControllerPitchInput() and AddControllerYawInput() make the pawn leave the ground again ...
Assistant
If the use of AddControllerPitchInput() or AddControllerYawInput() is causing unexpected behavior such as the pawn leaving the ground, it's possible that the camera and pawn setup needs further adjustment to properly isolate camera orientation from the pawn's movement mechanics. When making a first-person shooter (FPS) style game, typically, you want the character (or pawn) to rotate only on the yaw axis (for turning left and right) while keeping pitch movements (looking up and down) restricted to the camera alone.
Let's review and configure your pawn and camera to ensure that changes in pitch do not affect the pawn's position or cause it to leave the ground:
1. Initial Pawn and Camera Setup
Ensure your pawn is configured to properly segregate yaw (horizontal) and pitch (vertical) rotations:
cpp
// Constructor of your Pawn
AXpCollectorPawn::AXpCollectorPawn()
{
// Set this pawn to call Tick() every frame.
PrimaryActorTick.bCanEverTick = true;
// Create and attach components
player_mesh = CreateDefaultSubobject<UStaticMeshComponent>(TEXT("PlayerMesh"));
RootComponent = player_mesh;
player_camera = CreateDefaultSubobject<UCameraComponent>(TEXT("PlayerCamera"));
player_camera->SetupAttachment(RootComponent);
// Camera follows the head of the character, which rotates on the yaw axis
player_camera->bUsePawnControlRotation = true;
// Ensuring the pawn rotates only on the yaw axis
bUseControllerRotationYaw = true; // Allow yaw rotation for turning
bUseControllerRotationPitch = false; // Disable pitch (this should prevent the entire pawn from pitching)
bUseControllerRotationRoll = false; // Disabling roll generally makes sense
}
2. Handling Look Up and Turn Inputs
Ensure that you are correctly mapping inputs to only affect the intended rotation aspects:
cpp
Not yet included in a published release.
MoveForward
MoveRight
2. Modify the Move Functions:
Update the MoveForward and MoveRight methods to merely change the input state, not the velocity directly:
cpp
void AMyQuakePawn::MoveForward(float Value)
{
// Assume InputAxis is a float member that stores the forward/backward input value
InputAxis.X = FMath::Clamp(Value, -1.0f, 1.0f);
}
void AMyQuakePawn::MoveRight(float Value)
{
// Assume InputAxis is a float member that stores the right/left input value
InputAxis.Y = FMath::Clamp(Value, -1.0f, 1.0f);
}
Make sure to define InputAxis in your header file:
cpp
FVector InputAxis;
Summary
By modifying how the movement input is processed and applied, you keep the CurrentVelocity grounded in real-time player input, preventing any undesired continuous movement. Each frame resets CurrentVelocity, and only if there's active input will it affect the Pawn's location.
Make sure to compile your code after these changes. You will also have to test to ensure that this change integrates well with any other components or logic you have for handling movement, especially if you're planning to add more complex mechanics like bunny hopping or strafe jumping later.
3. Update Input Handling Methods:
As with the traditional input component, update how input influences velocity:
cpp
void AMyQuakePawn::MoveForward(float Value)
{
InputAxis.X = Value; // Set directly from input
}
void AMyQuakePawn::MoveRight(float Value)
{
InputAxis.Y = Value; // Set directly from input
}
void AMyQuakePawn::StartJump()
{
bIsJumping = true;
}
void AMyQuakePawn::StopJump()
{
bIsJumping = false;
}
Ensure your update method or handling in Tick is appropriate based on InputAxis.
4. Test and Debug
After making these changes, compile your code and test your pawn in Unreal Engine 5 to ensure inputs are behaving as expected. Debug any issues related to input bindings, or input values not updating correctly.
Using Enhanced Input, you gain more control and customizability over input handling, which can be particularly important for games requiring precise control schemes like those inspired by Quake’s dynamics.
#include "AXpCollectorPawn.h"
AXpCollectorPawn::AXpCollectorPawn()
{
PrimaryActorTick.bCanEverTick = true;
// Initialize the CameraComponent
CameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComponent"));
RootComponent = CameraComponent;
}
void AXpCollectorPawn::BeginPlay()
{
Super::BeginPlay();
}
void AXpCollectorPawn::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
// If we have some input
if (!CurrentVelocity.IsNearlyZero())
{
FVector NewLocation = GetActorLocation() + (CurrentVelocity * DeltaTime);
SetActorLocation(NewLocation);
}
}
void AXpCollectorPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
if (auto* EIC = Cast<UEnhancedInputComponent>(PlayerInputComponent))
{
EIC->BindAction(MoveForwardBackwardAction, ETriggerEvent::Triggered, this, &AXpCollectorPawn::MoveForwardBackward);
EIC->BindAction(MoveLeftRightAction, ETriggerEvent::Triggered, this, &AXpCollectorPawn::MoveLeftRight);
}
}
void AXpCollectorPawn::MoveForwardBackward(const FInputActionValue& Value)
{
// Take axis value from Enhanced Input and scale it
CurrentVelocity.X = Value.Get<float>() * 100.0f;
}
void AXpCollectorPawn::MoveLeftRight(const FInputActionValue& Value)
{
// Take axis value from Enhanced Input and scale it
CurrentVelocity.Y = Value.Get<float>() * 100.0f;
}
void AXpCollectorPawn::StartJump()
{
bIsJumping = true;
}
void AXpCollectorPawn::StopJump()
{
bIsJumping = false;
}
Additional Notes:
Camera Initialization: A camera component is initialized and attached to the pawn for providing a first-person view. Adjust its settings for your specific use case.
Movement Calculation: Movement functions take input values directly from actions and transform them into velocity components. The velocity is applied each frame in the Tick function.
Jump Implementation: Stub functions for jumping logic are in place (StartJump and StopJump). To enable jumping, you would typically use physics or adjust the Z component of CurrentVelocity depending on your game mechanics.
Game Setup: Don't forget to set up your pawn in the game world and configure input mappings in the project settings with action and axis mappings linked correctly as expected by the SetupPlayerInputComponent.
This class should provide a strong foundation for Quake-like movement using UE5's Enhanced Input System. You might adjust speed, handling additional movement intricacies like strafe-jumping or bunny hopping as you refine your movement mechanics further.
In this corrected edition, MoveForwardBackward and MoveLeftRight clearly differentiate between the control mechanisms for moving in the Y-direction (left-right) and X-direction (forward-backward), which mirrors traditional FPS controls.
Make sure your AXpCollectorPawn blueprint or C++ class setup uses the correct input mappings you defined in Project Settings > Input. Both action bindings set in this setup are triggered by the input system, and each should correctly modify CurrentVelocity based on player input, updating the pawn's location every tick.
Step 3: Add a Movement Input Member Variable
In your header (AXpCollectorPawn.h), declare a MoveInput FVector to store this frame's input values:
cpp
public:
// Add to AXpCollectorPawn class declaration
FVector MoveInput; // Used to store the current frame's movement input
Recap
This configuration ensures that CurrentVelocity is recomputed each frame based entirely on the current input. When there is no input (MoveInput.X and MoveInput.Y are zero), CurrentVelocity will also be zero, causing the pawn to remain stationary. This scheme is robust against lingering movement because it does not allow CurrentVelocity to persist beyond the current frame's input context.
Make sure all component responses and movements are calculated and applied only within the context of active input, thus minimizing the risk of unintended continuous movement. Lastly, remember to initialize MoveInput to zero to prevent uninitialized movement on spawn. Adjust these concepts according to the specific needs of your project and further features you might integrate.
// The arguments might need adjustment based on your actual setup.
void AXpCollectorPawn::MoveForwardBackward(const FInputActionValue& Value)
{
MoveInput.X = Value.Get<float>(); // Ensures that MoveInput.X is zero when no input
}
void AXpCollectorPawn::MoveLeftRight(const FInputActionValue& Value)
{
MoveInput.Y = Value.Get<float>(); // Ensures that MoveInput.Y is zero when no input
}
Initialization of MoveInput
Ensure MoveInput is initialized in the constructor of AXpCollectorPawn to avoid any initial erratic movement:
cpp
AXpCollectorPawn::AXpCollectorPawn()
{
PrimaryActorTick.bCanEverTick = true;
// Initialize components, etc.
CameraComponent = CreateDefaultSubobject<UCameraComponent>(TEXT("CameraComponent"));
RootComponent = CameraComponent;
// Initialize Move Input
MoveInput = FVector::ZeroVector; // Ensure it starts with zero
}
Validate Your Input Action Bindings
It's vital to check the bindings in the Unreal Editor settings and ensure that the actions are triggering as expected. Incorrect bindings or misconfigurations can lead to unexpected behavior.
By following these structures, you should be able to control your pawn's movement effectively without residual movement when the input ceases. If the problem persists, double-check all related input settings in the Unreal Editor and ensure your Enhanced Input Actions are properly set up and bound to actor functions.
3. Blueprint or Editor Adjustability
By exposing MoveSpeedMultiplier as a UPROPERTY with EditAnywhere and BlueprintReadWrite, you can adjust this variable directly in the Unreal Editor or via Blueprints, making it easy to tweak the speed during playtests without recompiling code.
4. Add Boost or Modifier Keys
If you want more dynamic control, such as allowing the player to "sprint" or move faster when holding a certain key, you would handle this by adjusting the speed multiplier conditionally based on additional input.
Then define functions to adjust the speed multiplier:
cpp
void AXpCollectorPawn::StartSprint()
{
MoveSpeedMultiplier *= 2.f; // Double the speed when sprinting
}
void AXpCollectorPawn::StopSprint()
{
MoveSpeedMultiplier /= 2.f; // Restore the original speed
}
Remember to handle potential issues with this simplistic multiplication/division approach (like making sure sprinting can't be toggled on and off rapidly to avoid multiplier buildup or depletion).
Summary
These approaches provide both static and dynamic ways to control the speed of your pawn's movement. Adjusting the MoveSpeedMultiplier provides a simple yet effective way to achieve your desired game feel and pace.
Tick Function: In the Tick method, ensure the position of the pawn is being updated based on current_velocity, which should be calculated from move_input. Here’s a sample implementation:
cpp
void AXpCollectorPawn::Tick(float DeltaTime) {
Super::Tick(DeltaTime);
// Calculate velocity from input
current_velocity = move_input * 100.0f; // Scale movement speed
// Update position
if (!current_velocity.IsNearlyZero()) {
FVector NewLocation = GetActorLocation() + (current_velocity * DeltaTime);
SetActorLocation(NewLocation);
}
}
Input Binding: Your SetupPlayerInputComponent function needs proper binding of actions to function callbacks. This seems to be appropriately handled but ensure your move_fb and move_lr function signatures exactly match what you're binding to, i.e., they expect a parameter of type const FInputActionValue&.
Additional Functionalities: For functionalities like jumping, make sure to handle it both in the physics calculation (if applicable) and visually. The actual implementation of start_jump() and stop_jump() would depend on whether you are using Unreal physics or custom logic.
Final Note
These suggestions and code examples should help you refine your implementation. Testing in the editor will be key to fine-tuning the behaviors and ensuring all parts work together seamlessly. If you have specific behaviors or features in mind (like complex movement dynamics, interaction systems), you can expand on this basic structure.
4. Use and Configuration of Enhanced Input Subsystem in BeginPlay
The addition of a mapping context to the Enhanced Input subsystem within BeginPlay is smart. Ensure that the mapping_context is properly set up with relevant mappings via the editor/other initialization code.
5. Future Enhancements
Jump Mechanic: Currently, start_jump() and stop_jump() just toggle a boolean flag. Consider implementing physical jump behavior using Unreal's physics engine (e.g., adding a vertical impulse).
Movement Speed Configurable: Rather than a hard-coded speed multiplier, consider making this configurable through a property as suggested previously.
Input Responsiveness: Depending on the gameplay, you might want to tweak input responsiveness and handling (e.g., smoothing or more complex input interpretations).
Overall
Your fundamental architecture for handling movement and input is established well. With these tweaks and observing best practices, your implementation will be more robust and ready for further enhancements like adding complex game mechanics or improving usability.
d. Test and Iterate
Quake’s movement system is notable for its precision and feel, which requires a lot of fine-tuning and testing with player feedback.
Conclusion:
To truly replicate Quake’s movement mechanics, you'll need to implement and customize physics and input handling far beyond basic forward/backwards/left/right movement to incorporate elements of speed, momentum, and precise air control. Given Unreal Engine's flexible physics and control systems, you can definitely achieve this, but it requires deep integration and testing to get the "feel" near what Quake offers.
In this modified Tick function:
The movement vector (NewVelocity) is normalized (using .GetSafeNormal()) when the input suggests diagonal movement. This keeps the speed constant regardless of the direction.
The original magnitude of speed for movement 1000.f is reapplied to the normalized vector, preserving the desired speed across all directions uniformly.
Testing and Tuning
After implementing normalization, test the character's movement in various directions. Ensure that the feel and responsiveness of the movement are maintained or improved. You might need to adjust the actual speed value (1000.f in the examples) depending on gameplay needs.
Using DeltaTime is a best practice in game development for achieving consistent timing and movement across various execution environments. If there are other aspects of frame rate management or game performance you’re uncertain about, feel free to ask!
5. Monitor System Performance:
It’s wise to monitor system performance and examine whether the high frame rate is introducing excessive system strain. Tools within Unreal Engine, like the Profiler, can help determine if certain aspects are consuming undue resources.
Summary
In high-FPS scenarios, it is crucial to scale operations that are time-sensitive using DeltaTime to ensure movements and actions remain consistent no matter the frame rate. Additionally, controlling maximum frame rates and using fixed physics steps are strategies to counter some high-FPS issues, ensuring that the game runs smoothly without overburdening hardware or causing logic errors. By conscientiously managing these factors, developers can provide an optimal balance between performance, hardware compatibility, and gameplay consistency.
c. Test Across a Range of Systems:
Testing your game on various hardware configurations will help ensure it performs consistently across different systems and helps identify any issues that may only appear at very high or low frame rates.
d. Implement Fixed Time Step for Physics:
For physics calculations, consider using fixed time steps where each physics update is processed in fixed intervals (e.g., 60 Hz), regardless of the frame rate. This helps prevent issues such as tunneling (where fast-moving objects pass through obstacles).
e. Monitor Performance Metrics:
Use tools like Unreal’s built-in profiler to monitor performance metrics and ensure that your game isn’t excessively taxing the hardware at high frame rates.
Conclusion
While high frame rates can vastly improve the gaming experience by making gameplay smoother and more responsive, they can also introduce challenges especially related to physics and resource consumption. Careful planning and testing across a range of frame rates are essential in ensuring that a game functions reliably and equitably no matter the player's hardware.
Frame Rate Capping or Dynamic Adjustments:
To prevent the system from potential overloads on machines capable of extremely high FPS, consider capping the frame rate to a maximum considered optimal for gameplay.
Further Investigation on Input Mechanics:
Depending on gameplay, check if the current per-frame input handling is optimal or if it needs buffering, particularly for actions like jumps which might have a different feeling on high versus low FPS setups.
Testing:
Cross-Frame Rate Testing: Test the gameplay at different frame rates (30 FPS, 60 FPS, 144 FPS, etc.) to ensure consistent behavior and feel. This testing can reveal if inputs feel too responsive or too sluggish, and whether movements seem consistent.
Profiler Use: Utilize Unreal’s profiling tools to check how the game performs under these varied conditions and where it might be unoptimized or too demanding.
Conclusion
Your AXpCollectorPawn is set up well to handle changes in FPS, particularly with the proper utilization of DeltaTime. Yet, depending on the game's specific needs (e.g., type of game, target hardware, input dynamics), further adjustments might be beneficial, particularly around input handling and frame rate management to optimally balance responsiveness and consistency.
Simplistic Approach — Direct Coordinate Manipulation:
On the other hand, directly changing the X or Y values of an actor’s location:
Is highly dependent on frame rates; at higher frame rates, the actor will move faster, which isn’t generally desired.
Does not naturally account for game time or physics—making it suitable only for very basic or static frame rate games where timing and physical realism are not concerns.
Can lead to gameplay that feels different across devices with different performance capabilities.
Conclusion:
Opting for a proper movement handling system using velocities and time deltas not only offers a more consistent and device-independent gameplay experience but also keeps the door open for more complex motion handling in future development, such as introducing acceleration/deceleration, handling collisions gracefully, and integrating with Unreal’s built-in physics systems effectively.
Step 4: Bind Input in SetupPlayerInputComponent
Ensure that you bind your new input axis mappings to the correct functions inside SetupPlayerInputComponent:
Verify that the camera is set to follow the controller's rotation. Assuming your camera is a child component of the pawn's root, it should naturally inherit the rotation settings configured above.
Final Integration and Testing
Compile your code and test the game in the Unreal Editor. You should now be able to look around using the mouse. Adjust the RotationSpeed values as necessary to get the desired responsiveness.
Step 3: Bind Input in SetupPlayerInputComponent
This remains the same as your initial setup to bind the axis movements:
Direct Control: This method gives you more direct control over how rotations are handled and applied, without involving the player controller.
Customization: It’s easier to implement custom behaviors like custom clamping angles, smoother interpolations, non-linear rotation speeds, etc.
Complexity and Maintenance: Directly managing rotations could lead to more complex code and potential issues with integrations like network replication or other Unreal Engine systems that expect rotation to be handled via the controller.
This method operates fully within your pawn logic, so you can adjust it without affecting other parts of the engine's player control system. It is beneficial in cases where you want precise control over the rotation mechanics or are implementing features not natively supported through the player controller interface.
General Game Development:
Use AddControllerPitchInput and AddControllerYawInput when working within the typical game framework provided by Unreal Engine, especially when developing standard first-person or third-person games. This method leverages Unreal’s robust back-end systems ensuring smooth, predictable, and network-compatible character control.
Specialized Applications or Custom Control Needs:
Opt for Direct Rotation Control when you need a level of precision or customization that goes beyond what the standard player controller and its input system offer. This is particularly relevant in cases like simulators, custom camera systems, or physics-driven interactive applications.
Ultimately, the choice should align with your project's needs, objectives, and the specific behaviors you want to implement. If conformity with Unreal's ecosystem is a priority for accuracy, consistency, and maintainability, then using the controller’s rotational inputs is typically the best choice. However, if your project demands unique rotational behavior not easily accomplished via the standard input system, direct manipulation of rotation might be necessary.
Step 3: Check Camera Attachment and Settings
Ensure that the camera is attached to the correct component (typically the root or a head bone, if applicable) and set up to follow the controller's rotation if it’s a first-person view:
cpp
player_camera = CreateDefaultSubobject<UCameraComponent>(TEXT("PlayerCamera"));
player_camera->SetupAttachment(RootComponent); // Attach it to the root or another appropriate component
player_camera->bUsePawnControlRotation = true; // Ensures the camera follows the head rotation
Step 4: Verify Input Bindings
Verify that the input bindings are correctly set up as previously described, and that they’re properly calling your intended rotation methods on input events.
Testing
Once these settings are in place, test your pawn again by moving and using the mouse to turn. The pawn or the camera (depending on your game's perspective and setup) should now visually reflect changes in direction based on mouse movement.
If adjustments to these settings do not resolve your issue, consider double-checking how the input is processed or looking for any overrides or conflicting settings that might block or alter controller rotation behavior.
void AXpCollectorPawn::Turn(float Rate)
{
// Yaw update based on turn rate and frame time
AddActorLocalRotation(FRotator(0.f, Rate * RotationSpeed * GetWorld()->GetDeltaSeconds(), 0.f));
}
void AXpCollectorPawn::LookUp(float Rate)
{
// Pitch rotation (you might need to clamp this value to prevent full rotation)
FRotator NewRotation = GetActorRotation();
NewRotation.Pitch = FMath::Clamp(NewRotation.Pitch + Rate * RotationSpeed * GetWorld()->GetDeltaSeconds(), MinPitch, MaxPitch);
SetActorRotation(NewRotation);
}
3. Setting Input Component Bindings
Make sure your input bindings in SetupPlayerInputComponent are properly configured to call these new or revised functions when input events occur:
Using GetActorForwardVector() and GetActorRightVector() alongside manual rotation offers full control and avoids dependencies on the default controller systems, which can be particularly beneficial if your game requires non-standard behaviors that are not supported by the standard Unreal Engine controller system. This method also simplifies certain multiplayer behaviors, as it reduces the dependency on replicated controller states.
However, remember this approach might require more complex handling of camera logic, collision detection, and response if you diverge significantly from traditional mechanisms. Also, ensure syncing these manual methods in multiplayer settings if needed.
// Called to bind functionality to input
void AXpCollectorPawn::SetupPlayerInputComponent(
UInputComponent* PlayerInputComponent) {
Super::SetupPlayerInputComponent(PlayerInputComponent);
if (auto* eic = CastChecked(PlayerInputComponent)) {
eic->BindAction(move_fb_action,
ETriggerEvent::Triggered,
this,
&AXpCollectorPawn::move_fb);
Make sure that new_velocity is being normalized only when necessary and then scaled by the speed factor, particularly handling diagonal normalizing correctly:
cpp
// Called every frame
void AXpCollectorPawn::Tick(const float DeltaTime) {
Super::Tick(DeltaTime);
if (!FMath::IsNearlyZero(move_input.Size())) {
// Normalizing the combined movement input (handles diagonal movement correctly)
FVector normalizedVelocity = move_input.GetSafeNormal() * GSpeed_Factor;
SetActorLocation(GetActorLocation() + normalizedVelocity * DeltaTime);
}
// Reset move_input after applying movement
move_input = FVector::ZeroVector;
}
This modification ensures that the input vectors for different directions are combined properly, allowing for correctly normalized diagonal movement. The normalization ensures that moving diagonally doesn't result in faster movement than moving straight along an axis. Apply these corrections, and your pawn should be able to move diagonally as intended.
movementVector
directionalInput
void AXpCollectorPawn::Tick(float DeltaTime)
{
Super::Tick(DeltaTime);
// Handle bhopping: check if the player is about to land and wants to jump again
if (bWantsToJump && IsNearlyGrounded())
{
Jump();
}
}
void AXpCollectorPawn::Jump()
{
if (CanJump()) // Your logic to determine if a jump is possible
{
// Apply jump force
FVector JumpVelocity = FVector(0, 0, JumpZVelocity);
// Preserve horizontal velocity
JumpVelocity.X += GetVelocity().X;
JumpVelocity.Y += GetVelocity().Y;
// Set the new velocity including the jump component
GetCharacterMovement()->Velocity = JumpVelocity;
bWantsToJump = false;
}
}
void AXpCollectorPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
PlayerInputComponent->BindAxis("MoveForward", this, &AXpCollectorPawn::MoveForward);
PlayerInputComponent->BindAxis("MoveRight", this, &AXpCollectorPawn::MoveRight);
PlayerInputComponent->BindAxis("Turn", this, &AXpCollectorPawn::AddControllerYawInput);
PlayerInputComponent->BindAxis("LookUp", this, &AXpCollectorPawn::AddControllerPitchInput);
PlayerInputComponent->BindAction("Jump", IE_Pressed, this, &AXpCollectorPawn::StartJump);
PlayerInputComponent->BindAction("Jump", IE_Released, this, &AXpCollectorPawn::StopJump);
}
void AXpCollectorPawn::StartJump()
{
bWantsToJump = true; // Indicate that player wants to jump
}
Considerations:
Tuning is Crucial: The magic of bhopping often comes from finely-tuned physics and input handling. You’ll likely need to spend time adjusting the parameters and testing the feel to replicate the precise bhopping behavior seen in games like Quake or Counter-Strike.
Replication in Multiplayer: Ensure that your bhopping mechanics are properly replicated across the network if you are developing a multiplayer game. This might involve handling and synchronizing states like bWantsToJump and manually managing replication of velocity changes.
By focusing on how movement and jumps are handled while maintaining basic player control through the existing Unreal Engine player controller, you can effectively implement advanced movement techniques like bunny hopping.
if (auto* eic = CastChecked(PlayerInputComponent)) {
eic->BindAction(move_fb_action,
ETriggerEvent::Triggered,
this,
&AXpCollectorPawn::move_fb);
bUseControllerRotationYaw: This setting is set to true because for FPS games, you do want the pawn to rotate left and right along with the camera.
Further Verification
Ensure that camera rotation only affects viewing direction and not movement mechanics.
Make sure the pitch changes do not inadvertently translate into movement or displacement along the Z-axis.
By isolating the camera's pitch movements from the pawn's body rotations and movements, you can achieve a standard FPS experience where the player can look upward or downward without affecting the character's grounding and movement along the game field.
SetupPlayerInputComponent
cpp
void AXpCollectorPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
// Assuming you've setup actions names LookUp in the Engine's Input Settings
PlayerInputComponent->BindAxis("LookUp", this, &AXpCollectorPawn::LookUp);
}
void AXpCollectorPawn::LookUp(float Rate)
{
if (Controller && Rate != 0.0f)
{
// This directly adds to the controller's pitch. Adjust Rate by multiplying with a sensitivity factor if needed
Controller->AddPitchInput(Rate);
}
}
Testing and Debugging
After making these adjustments, test the camera movement. If the problem persists:
Debug Output: Use UE_LOG calls or breakpoints to verify if the LookUp method gets called and if Rate is non-zero.
Project Settings: Double-check your input bindings in the Unreal Editor under Edit > Project Settings > Input to ensure the axes are mapped correctly to the mouse movements or other input devices.
This should allow the camera to freely look up and down without affecting the pawn's grounding, and solve the rotation lock issue you're experiencing.
SetupPlayerInputComponent
cpp
void AXpCollectorPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
PlayerInputComponent->BindAxis("LookUp", this, &AXpCollectorPawn::LookUp);
// Make sure "LookUp" has been set up in Project Settings > Input correctly.
}
This setup assumes that your mouse or input axis for looking up and down is correctly configured in Unreal Engine's input settings (found under Edit > Project Settings > Input).
This should resolve the issues about using undefined methods and will correctly allow you to control the camera's pitch following the proper Unreal Engine concepts for handling player-controlled rotation. Make sure your input configurations, controller settings, and function bindings are synchronized to get the expected behavior.
4. Attach and Configure the Input Component
Ensure you bind the axis for looking up/down properly in SetupPlayerInputComponent. Double-check to be certain that "LookUp" is correctly configured in the Input settings under the Engine menu.
Make sure that in your project settings, under Edit > Project Settings > Input, the axis mapping for "LookUp" corresponds to the correct axis (usually Mouse Y). Adjust the scale factor to control the sensitivity and the direction (invert the axis by using a negative value if necessary).
Final Checks
Verify Camera Attachment: Ensure that the camera is properly attached to the pawn and tests both in the editor and during runtime. Look rotation should only affect the camera and not the pawn's altitude.
Test Input Sensitivity: Adjust LookUp sensitivity if the response feels too sluggish or too sensitive.
By ensuring that the pawn and the camera have their responsibilities appropriately delegated (the camera for vertical look and the pawn for horizontal orientation in this case), you should be able to eliminate unwanted vertical movement ("flying") while maintaining responsive vertical look controls.
Avoiding Direct Manipulation of Rotators:
Whenever possible, use Unreal's built-in methods for rotation transformations, as they handle many underlying complexities for you. When direct manipulation is unavoidable (as in some cases for camera control), testing across a range of motion to ensure no unexpected behaviors occur is essential.
By understanding the peculiarities of how Unreal handles rotations and ensuring that your manipulations consider these aspects, you can achieve a robust and player-friendly camera system. Your solution and these enhancements will help ensure that the camera system remains intuitive and error-free.
4. Understanding Gimbal Lock and Rotator Behavior
FRotator in Unreal maintains angles in a [-180, 180] range. Exceeding these values could cause angles to wrap around, potentially bypassing clamping logic. If your gameplay allows extreme looking angles or rapid movement, consider how exceeding typical rotator bounds might affect behavior.
5. Alternative Clamping Strategy
If direct clamping on FRotator isn’t effective, you might consider using the Normalized version or manually clamping the value as you apply rotations:
This ensures that you directly control and clamp the modified value before it’s applied as rotation.
6. Testing and Calibration
After implementing these suggestions, carefully test how the camera behaves in different looking scenarios. Adjust RotationSpeed, MinPitch, and MaxPitch according to the desired responsiveness and limits of the game's camera control.
By refining how you apply and clamp rotations, ensuring that the sequence of operations is correct, and keeping a close eye on the actual runtime values, you can achieve the desired up and down viewing restrictions without unintended behavior.
Using RotateVector or transformation functions that Unreal's UKismetMathLibrary or FTransform classes provide.
5. Continuous Monitoring and Adjustment
Ensure continuous runtime checking and adjustment of rotations, like regular monitoring and clamping of pitch angles, during events such as tick updates or after physics calculations.
For adjustments that involve significant shifts in viewpoint or orientation (e.g., snapping the camera to a target), consider implementing smooth transitions such as lerp or slerp (spherical linear interpolation for quaternions) to blend the movement over time:
cpp
FRotator TargetRotation = FRotator(TargetPitch, TargetYaw, 0);
FRotator CurrentRotation = FMath::Lerp(GetControlRotation(), TargetRotation, 0.1f); // Adjust the lerp rate as needed.
GetController()->SetControlRotation(CurrentRotation);
By handling rotations more carefully and employing Unreal Engine's more robust systems for dealing with rotational data, you can avoid many common pitfalls associated with direct manipulations of FRotator objects. This approach helps in maintaining a stable and reliable camera system in your game.
void AXpCollectorPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
PlayerInputComponent->BindAxis("Turn", this, &AXpCollectorPawn::Turn);
PlayerInputComponent->BindAxis("LookUp", this, &AXpCollectorPawn::LookUp);
}
void AXpCollectorPawn::Turn(float Value)
{
AddControllerYawInput(Value);
}
void AXpCollectorPawn::LookUp(float Value)
{
// Direct control of pitch, applied to the controller which the camera follows if bUsePawnControlRotation is true.
AddControllerPitchInput(Value);
}
3. Configuring Inputs in Unreal's Settings:
Make sure the axis mappings for "Turn" (often linked to Mouse X) and "LookUp" (often linked to Mouse Y) are correctly set up in the project settings under Edit -> Project Settings -> Input.
These settings, the pawn and camera configuration, and the way inputs are handled establish a direct relationship between player controller inputs (AddControllerPitchInput and AddControllerYawInput) and camera movement in a typical FPS view setup in Unreal Engine. This alignment ensures that camera rotation feels intuitive to the player, following standard practices in game camera control behavior.
void AXpCollectorPawn::SetupPlayerInputComponent(UInputComponent* PlayerInputComponent)
{
Super::SetupPlayerInputComponent(PlayerInputComponent);
PlayerInputComponent->BindAxis("LookUp", this, &AXpCollectorPawn::LookUp);
PlayerInputComponent->BindAxis("Turn", this, &AXpCollectorPawn::Turn);
}
void AXpCollectorPawn::Turn(float Rate)
{
AddControllerYawInput(Rate);
}
void AXpCollectorPawn::LookUp(float Rate)
{
// This should affect only the camera's look up/down if the pawn's pitch control is disabled
AddControllerPitchInput(Rate);
}
3. Verifying Camera Configuration
Double-check that the camera configuration is correct:
bUsePawnControlRotation: This setting on the camera component ensures that the camera will follow the orientation dictated by the controller, but with bUseControllerRotationPitch=false, pitch changes should only affect the camera, not the pawn’s movement or position.
4. Testing and Debugging
After configuring as above, test thoroughly in your game environment. Watch out specifically for:
Does turning left/right correctly rotate the pawn?
Does looking up/down only change where the camera is pointing without lifting the pawn off the ground?
If the pawn continues to exhibit unintended vertical (pitch-related) movement despite these settings, consider delving into any additional scripts or inherited settings that might be causing unexpected behavior such as movement logic directly tied into pitch input events.
Conclusion
Settings and careful control over input handling should resolve issues of pitch movement affecting vertical positioning. If you continue to experience issues after implementing these suggestions, it might be beneficial to check through any custom movement logic you may have implemented that could be contributing to the problem.