= 0.3f; if(!A->bInfiniteMass){ A->ApplyMoveForce(f); if(!A->IsVehicle() || !CWorld::bNoMoreCollisionTorque) A->ApplyTurnForce(f, pointposA); } return true; } }else if(!B->bInfiniteMass) B->SetIsStatic(false); } } if(B->GetIsStatic()) return false; if(!B->bInfiniteMass) B->AddToMovingList(); } // B is not static if(A->bPedPhysics && B->bPedPhysics){ // negative if A is moving towards B speedA = DotProduct(A->m_vecMoveSpeed, colpoint.normal); // positive if B is moving towards A // not interested in how much B moves into A apparently? // only interested in cases where A collided into B speedB = DotProduct(B->m_vecMoveSpeed, colpoint.normal); float speedSum = Max(0.0f, DotProduct(B->m_vecMoveSpeed, colpoint.normal)); // A has moved into B if(speedA < speedSum){ if(A->bHasHitWall) eA = speedSum; else eA = speedSum - (speedA - speedSum) * (A->m_fElasticity+B->m_fElasticity)/2.0f; impulseA = (eA-speedA) * A->m_fMass * massFactorA; if(!A->bInfiniteMass) A->ApplyMoveForce(colpoint.normal
= 1.4f; fA.y = 1.4f; if(colpoint.normal.z < 0.7f) fA.z = 0.3f; if(A->GetStatus() == STATUS_PLAYER) pointposA = 0.8f; if(CWorld::bNoMoreCollisionTorque){ A->ApplyFrictionMoveForce(fA-0.3f); A->ApplyFrictionTurnForce(fA-0.3f, pointposA); } } if(B->IsVehicle() && !B->bHasHitWall){ fB.x = 1.4f; fB.y = 1.4f; if(-colpoint.normal.z < 0.7f) fB.z = 0.3f; if(B->GetStatus() == STATUS_PLAYER) pointposB = 0.8f; if(CWorld::bNoMoreCollisionTorque){ #ifdef FIX_BUGS B->ApplyFrictionMoveForce(fB-0.3f); B->ApplyFrictionTurnForce(fB-0.3f, pointposB); #else A->ApplyFrictionMoveForce(fB-0.3f); A->ApplyFrictionTurnForce(fB-0.3f, pointposB); #endif } } if(!A->bInfiniteMass){ A->ApplyMoveForce(fA); A->ApplyTurnForce(fA, pointposA); } if(!B->bInfiniteMass){ if(B->bIsInSafePosition) B->UnsetIsInSafePosition(); B->ApplyMoveForce(fB); B->ApplyTurnForce(fB, pointposB); } return true; } } return false; } how to make same behavior for jumping and falling in my code (with minimal change): inline void Player::Update(float deltaTime) { glm::vec3 currentPosition = GetPosition(); glm::vec3 newPosition = currentPosition; bool positionChanged = false; // Apply gravity and forward movement when jumping or falling if (m_isJumping || m_isFalling) { // Apply gravity to vertical movement if (m_isJumping) { m_jumpVelocity -= m_gravity * deltaTime; newPosition.y += m_jumpVelocity * deltaTime; if (m_jumpVelocity <= 0) { m_isJumping = false; m_isFalling = true; } } else if (m_isFalling) { float fallGravityScale = 2.0f; m_fallVelocity = std::min(m_fallVelocity + (m_gravity * fallGravityScale * deltaTime), 30.0f); // Limit the max fall speed newPosition.y -= m_fallVelocity * deltaTime; } // Continue forward movement during the jump and fall glm::quat rotation = GetRotation(); glm::vec3 forward = glm::normalize(rotation * glm::vec3(0, 0, 1)); // Forward direction newPosition += forward * m_jumpForwardSpeed * deltaTime; positionChanged = true; } // Check for ground collision float rayLength = 3.0f; // Adjust this to match your world's height glm::vec3 rayStart = currentPosition + glm::vec3(0, 0.1f, 0); glm::vec3 rayEnd = rayStart - glm::vec3(0, rayLength, 0); auto hitResult = m_world->RaycastWithPlayerCollision(rayStart, rayEnd, this); if (hitResult) { glm::vec3 hitPosition = hitResult; float groundY = hitPosition.y; if (newPosition.y <= groundY + 0.1f) { newPosition.y = groundY + 0.1f; // Keep slightly above ground if (m_isJumping || m_isFalling) { m_isJumping = false; m_isFalling = false; m_fallVelocity = 0; positionChanged = true; } } } else if (!m_isFalling && !m_isJumping) { m_isFalling = true; positionChanged = true; } // Apply the new position if (positionChanged) { SetPosition(newPosition); } } class Player { bool m_isJumping; bool m_isFalling; float m_jumpVelocity; float m_fallVelocity; float m_jumpHeight; float m_gravity; float m_jumpForwardSpeed; public: Player(dtCrowd crowd, World world); ~Player(); void Update(float deltaTime); void SetRotation(const glm::quat& rotation); glm::quat GetRotation() const; void SetPosition(const glm::vec3& position); glm::vec3 GetPosition() const; void SetLookAt(const glm::vec3& target); glm::vec3 GetLookAt() const; void MoveTo(const glm::vec3& destination); void SetServer(uint16_t serverId); uint16_t GetServer() const; void SetSpeed(const glm::vec3& speed); glm::vec3 GetSpeed() const; bool CalculatePathTo(const glm::vec3& destination); std::pair<glm::vec3, glm::vec3> GetBoundingBox() const; void Jump() { if (!m_isJumping && !m_isFalling) { m_isJumping = true; m_jumpVelocity = sqrt(2 * m_gravity * m_jumpHeight); // Set a forward speed for the jump (e.g. 4.0f) m_jumpForwardSpeed = 4.0f; // Adjust as needed } } private: dtCrowd m_crowd; glm::quat m_rotation; glm::vec3 m_lookAt; glm::vec3 m_position; uint16_t m_serverId; glm::vec3 m_moveSpeed; int m_agentIndex; bool m_ProcessMoveToPoint; World
To replicate GTA San Andreas's jumping and falling behavior in your Player class with minimal changes, you'll need to incorporate some of the key mechanics from the GTA SA code into your existing structure. This involves handling physics-based movement, state transitions, and collision responses more robustly.
Here's a step-by-step guide to achieve this:
Implement Physics-Based Movement:
Instead of directly manipulating the player's position based on velocity, apply forces that affect the player's movement. This approach allows for more realistic interactions, such as applying gravity, air resistance, and handling collisions naturally.
Manage States for Jumping and Falling:
Use a state machine to handle different player states like Idle, Running, Jumping, and Falling. This helps in organizing behavior and transitions between these states.
Handle Jump Initialization and Completion:
When the player initiates a jump, apply an upward force and set the state to Jumping. Once the jump force is exhausted, transition to the Falling state. Similarly, detect when the player lands to revert to the Idle or Running state.
Integrate Collision Detection and Response:
Use raycasting or collision detection to determine when the player is on the ground or has hit an obstacle. This will help in accurately handling landing and preventing the player from falling through the ground.
Incorporate Air Resistance and Friction:
Apply air resistance to simulate the slowing down of movement while in the air and friction when the player is on the ground to simulate realistic stopping behavior.
Detailed Implementation
Below is the modified Player class and Update method incorporating the above steps inspired by the GTA SA code:
#include <glm/glm.hpp>
#include <glm/gtc/quaternion.hpp>
#include <algorithm>
#include <cmath>
// Constants
const float GRAVITY = 9.81f;
const float MAX_FALL_VELOCITY = 30.0f;
const float JUMP_FORCE = 8.5f; // Adjust as needed
const float MASS = 70.0f; // Player mass
const float TURN_MASS = 100.0f; // Player turn mass
const float AIR_RESISTANCE = 0.4f / MASS;
const float ELASTICITY = 0.05f;
// Placeholder for world and collision detection
class World {
public:
bool Raycast(const glm::vec3& start, const glm::vec3& end, glm::vec3& hitPos) {
// Implement your raycast logic here
// Return true if hit, false otherwise
return false;
}
bool TestSphere(const glm::vec3& position, float radius) {
// Implement sphere collision test here
return false;
}
};
// Placeholder for applying forces
class CPhysical {
public:
glm::vec3 m_vecMoveSpeed;
glm::vec3 m_vecTurnSpeed;
void ApplyMoveForce(const glm::vec3& force) {
m_vecMoveSpeed += force / MASS;
}
void ApplyAirResistance(float deltaTime) {
if (AIR_RESISTANCE > 0.1f) {
float f = std::pow(AIR_RESISTANCE, deltaTime);
m_vecMoveSpeed *= f;
m_vecTurnSpeed *= f;
}
else {
float f = std::pow(1.0f / std::abs(AIR_RESISTANCE * 0.5f * glm::dot(m_vecMoveSpeed, m_vecMoveSpeed) + 1.0f), deltaTime);
m_vecMoveSpeed *= f;
m_vecTurnSpeed *= 0.99f;
}
}
void ApplyGravity(float deltaTime) {
m_vecMoveSpeed.y -= GRAVITY * deltaTime;
}
// Additional physics methods can be added here
};
class Player : public CPhysical {
public:
bool m_isJumping;
bool m_isFalling;
float m_jumpVelocity;
float m_fallVelocity;
float m_jumpHeight;
float m_gravity;
float m_jumpForwardSpeed;
glm::quat m_rotation;
glm::vec3 m_position;
glm::vec3 m_lookAt;
World* m_world;
Player(World* world)
: m_isJumping(false), m_isFalling(false), m_jumpVelocity(0.0f),
m_fallVelocity(0.0f), m_jumpHeight(4.0f), m_gravity(GRAVITY),
m_jumpForwardSpeed(4.0f), m_world(world) {}
~Player() {}
void Update(float deltaTime);
void Jump();
// ... other methods as previously defined
// Position and rotation methods
void SetRotation(const glm::quat& rotation);
glm::quat GetRotation() const;
void SetPosition(const glm::vec3& position);
glm::vec3 GetPosition() const;
// ... other methods
};
// Method implementations
inline void Player::SetRotation(const glm::quat& rotation) {
m_rotation = rotation;
// Update look-at based on new rotation
m_lookAt = m_position + glm::rotate(m_rotation, glm::vec3(0.0f, 0.0f, -1.0f));
}
inline glm::quat Player::GetRotation() const {
return m_rotation;
}
inline void Player::SetPosition(const glm::vec3& newPosition) {
m_position = newPosition;
}
inline glm::vec3 Player::GetPosition() const {
return m_position;
}
void Player::Jump() {
if (!m_isJumping && !m_isFalling) {
m_isJumping = true;
// Apply an upward force instead of setting velocity directly
ApplyMoveForce(glm::vec3(0.0f, std::sqrt(2 * m_gravity * m_jumpHeight), 0.0f));
// Set a forward speed for the jump
m_jumpForwardSpeed = 4.0f; // Adjust as needed
}
}
inline void Player::Update(float deltaTime) {
glm::vec3 newPosition = m_position;
bool positionChanged = false;
// Handle states and apply forces
if (m_isJumping || m_isFalling) {
if (m_isJumping) {
// Gravity is already applied in physics, so just handle state transitions
if (m_vecMoveSpeed.y <= 0) {
m_isJumping = false;
m_isFalling = true;
}
}
if (m_isFalling) {
// Air resistance is handled in physics
// Optionally, you can limit fall velocity
m_fallVelocity = std::min(m_fallVelocity + (m_gravity * 2.0f * deltaTime), MAX_FALL_VELOCITY);
// Apply forward movement
glm::vec3 forward = glm::normalize(glm::rotate(m_rotation, glm::vec3(0, 0, 1)));
ApplyMoveForce(forward * m_jumpForwardSpeed);
}
// Apply gravity
ApplyGravity(deltaTime);
// Apply air resistance
ApplyAirResistance(deltaTime);
positionChanged = true;
}
// Collision detection with the ground
float rayLength = 3.0f; // Adjust based on your world
glm::vec3 rayStart = m_position + glm::vec3(0, 0.1f, 0);
glm::vec3 rayEnd = rayStart - glm::vec3(0, rayLength, 0);
glm::vec3 hitPosition;
bool hitGround = m_world->Raycast(rayStart, rayEnd, hitPosition);
if (hitGround) {
float groundY = hitPosition.y;
if (m_position.y <= groundY + 0.1f) {
m_position.y = groundY + 0.1f; // Keep slightly above ground
if (m_isJumping || m_isFalling) {
m_isJumping = false;
m_isFalling = false;
m_fallVelocity = 0;
m_vecMoveSpeed.y = 0.0f; // Reset vertical speed
m_vecMoveSpeed.x = 0.0f; // Reset horizontal speed if needed
m_vecMoveSpeed.z = 0.0f; // Reset horizontal speed if needed
positionChanged = true;
// Optionally trigger landing animations or callbacks here
}
}
}
else if (!m_isFalling && !m_isJumping) {
m_isFalling = true;
positionChanged = true;
}
// Update position based on move speed
if (positionChanged) {
m_position += m_vecMoveSpeed * deltaTime;
SetPosition(m_position);
}
}
Explanation of Changes
Physics-Based Forces:
ApplyMoveForce: Instead of directly modifying the position based on velocity, forces are applied to influence the player's movement. This is similar to how GTA SA uses ApplyMoveForce to affect m_vecMoveSpeed.
ApplyGravity: A method that applies gravity to the player's vertical speed.
ApplyAirResistance: Simulates air resistance by reducing the player's speed over time.
State Management:
Jumping and Falling States: The m_isJumping and m_isFalling flags manage the player's current state. Transitions between these states are handled based on the player's vertical speed and collision with the ground.
Jump Method:
Applying Upward Force: When the player jumps, an upward force is applied instead of directly setting the jump velocity. This makes the jump feel more natural and physics-based.
Forward Movement: A forward force (m_jumpForwardSpeed) is applied to simulate forward motion during the jump.
Update Method:
State-Based Force Application: Depending on whether the player is jumping or falling, appropriate forces are applied.
Collision Detection: Raycasting is used to detect collision with the ground. Upon landing, the player's vertical and horizontal speeds are reset, and the state is transitioned back to idle or running.
Position Update: The player's position is updated based on the accumulated move speed affected by the applied forces and physics calculations.
Simplified Collision Response:
For simplicity, this implementation assumes basic collision handling. Depending on your game's requirements, you might need a more robust collision response system similar to GTA SA's ApplyCollision method.
Additional Recommendations
Animation Handling:
To closely mimic GTA SA, integrate animations for jumping, falling, and landing. Trigger animation states based on the player's current state.
Callbacks for Landing:
Implement callbacks or events that get triggered upon landing to handle post-jump logic, such as resetting states or triggering sound effects.
Air Control:
Allow some control over the player's movement while in the air by adjusting the forward force based on player input, similar to how GTA handles air movement.
Collision Margins and Response:
Enhance collision detection by considering margins and more detailed responses, ensuring the player interacts correctly with various surfaces and obstacles.
Fine-Tuning Physics Parameters:
Adjust constants like GRAVITY, JUMP_FORCE, MASS, and AIR_RESISTANCE to achieve the desired feel that closely resembles GTA SA's jumping and falling mechanics.
By integrating these physics-based approaches and state management strategies, your Player class will exhibit jumping and falling behaviors akin to those in GTA San Andreas with minimal structural changes to your existing code.