Sorry for the miserable english,
I'm working on the collision resolution of a top down racing game. The detection of the collision is made out of an image that contains two colors(white being a wall and black being not a wall). I just look at if the player(the car) middle position is inside the white color on the image.
this part works fine.
When it comes to resolution I'm getting some weird bugs. I'm suppossed to make sure the car stay in the track and cannot get out of it.
My broken solution goes like this: 1. create a vector named "Distance" that contain the substraction of the current position to the previous 2. normalise the Distance vector between 0 and 1 3. substract this normalised Distance vector to the current position until the player isn't on the white color. 4. cancel the velocity of the player(I don't plan on keeping it like that)
it sounds good in my my head but when I apply it I get some segmentation fault and occassionaly some teleportation.
the following code is in written using the SFML library and it's my attempt on making the collision. the player.update() call at the end only moves and rotate car.
void RacingMode::update(const sf::Time& deltaTime)
{
static sf::Vector2f prevPos(0,0);
static sf::Vector2f currPos(0,0);
currPos = sf::Vector2f(player.getPosition().x, player.getPosition().y);
if(raceTrack.getPixelColor(sf::Vector2u(currPos.x, currPos.y)) != sf::Color::Black){
sf::Vector2f dist;
dist.x = currPos.x - prevPos.x;
dist.y = currPos.y - prevPos.y;
dist.x = dist.x / sqrt(dist.x*dist.x + dist.y*dist.y);
dist.y = dist.y / sqrt(dist.x*dist.x + dist.y*dist.y);
sf::Vector2f newPos(0,0);
float i = 0.0;
do{
newPos = currPos - dist*i;
i+= 0.01;
}while(raceTrack.getPixelColor(sf::Vector2u(newPos.x, newPos.y)) != sf::Color::Black);
currPos = newPos;
player.setPosition(newPos);
player.setVelocity(0);
}
prevPos = currPos;
player.update(deltaTime);
}
I'd be grateful to anyone who can point out how I failed my attempt( or can propose other way of solving the problem)