Hello, i'm currently working on a simple game and i have a problem.
There are 2 problems, one that the player can sometimes jump higher, and second that the player can instantly stop at a platform. I kinda know where the problems are, but i don't know how can i fix that.
VIDEO OF THE PROBLEM: problem fixed.
Important variables:
float gravity = 2000.f
Code (only interesting parts)
Part of Player.cpp
void Player::move() {
//jump
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && canJump) {
jumpAnimation.applyAnimation(50, 0.1f, 100, 0);
canJump = false;
playerVelocity.y = -sqrtf(2.0f * gravity * jumpHeight);
}
playerVelocity.y += gravity * deltaTime;
hitbox.move(playerVelocity * deltaTime);
}
void Player::onCollision(sf::Vector2f direction)
{
if (direction.x < 0.0f) {
//Collision on left
playerVelocity.x = 0.0f;
}
else if (direction.x > 0.0f) {
//Collision on right
playerVelocity.x = 0.0f;
}
if (direction.y < 0.0f) {
//Collision on bottom
playerVelocity.y = 0.0f;
canJump = true;
}
else if (direction.y > 0.0f) {
//Collision on top
playerVelocity.y = 0.0f;
canJump = false;
}
}
and part of Collider.cpp
bool Collider::checkCollision(Collider& other, sf::Vector2f& direction, float mass)
{
sf::Vector2f otherPosition = other.GetPosition();
sf::Vector2f otherHalfSize = other.GetHalfSize();
sf::Vector2f thisPosition = GetPosition();
sf::Vector2f thisHalfSize = GetHalfSize();
float deltaX = otherPosition.x - thisPosition.x;
float deltaY = otherPosition.y - thisPosition.y;
float intersectX = abs(deltaX) - (otherHalfSize.x + thisHalfSize.x);
float intersectY = abs(deltaY) - (otherHalfSize.y + thisHalfSize.y);
if (intersectX < 0.0f && intersectY < 0.0f)
{
//clamping
mass = std::min(std::max(mass, 0.0f), 1.0f);
if (intersectX > intersectY)
{
if (deltaX > 0.0f)
{
Move(intersectX * (1.0f - mass), 0.0f);
other.Move(-intersectX * mass, 0.0f);
direction.x = 1.0f;
direction.y = 0.0f;
}
else
{
Move(-intersectX * (1.0f - mass), 0.0f);
other.Move(intersectX * mass, 0.0f);
direction.x = -1.0f;
direction.y = 0.0f;
}
}
else
{
if (deltaY > 0.0f)
{
Move(0.0f, intersectY * (1.0f - mass));
other.Move(0.0f, -intersectY * mass);
direction.x = 0.0f;
direction.y = 1.0f;
}
else
{
Move(0.0f, -intersectY * (1.0f - mass));
other.Move(0.0f, intersectY * mass);
direction.x = 0.0f;
direction.y = -1.0f;
}
}
return true;
}
return false;
}
Because the code is big i'll explain everything.
Note that in Player.cpp in class onCollision there is a thing that tracks where the player is colliding (top, left, rigth etc.) and when player collides on bottom the playerVelocity.y changes instantly to 0, and thats the problem, i dont know how to fix this, i dont have any idea, so thats beacouse im creating this topic. Thanks for the help