SFML community forums
Help => General => Topic started by: Bonafide on March 05, 2009, 08:21:59 pm
-
Hey guys,
I've tried searching the forums for a solution, and I've found some helpful threads that have given me some clues as how the Intersect() function works, but I just can't get it to work.
I'm simply trying to get a block to stop moving when it collides with another, stationary block.
Here's the code:
float left1, left2, right1, right2, top1, top2, bottom1, bottom2;
left1 = Sprite.GetPosition().x;
left2 = Spr.GetPosition().x;
right1 = left1 - Sprite.GetSize().x;
right2 = left2 - Spr.GetSize().x;
top1 = Sprite.GetPosition().y;
top2 = Spr.GetPosition().y;
bottom1 = top1 + Sprite.GetSize().y;
bottom2 = top2 + Sprite.GetSize().y;
sf::FloatRect Rect(left1, top1, right1, bottom1);
sf::FloatRect Rect2(left2, top2, right2, bottom2);
// Get elapsed time
float ElapsedTime = App.GetFrameTime();
// Move the sprite
if(Rect.Intersects(Rect2))
{
cout << 1;
}
else
{
// Key
}
The collision of the two sprites just won't work, Sprite just runs through Spr.
-
Why are you computing your "right" values as "left - width" instead of "left + width" ??
-
Heh, I did not catch that, but it finally works, thank you!
-
EDIT: Nevermind, this problem has been resolved.
Bump.
hey guys, I've seem to hit another road bump. Collision is now working, and I have made it so that if the blocks do collide, my moving block will move back a few units from the stationary block. However, if I hold a movement button (say the left key for this example) and make the block "stutter/jitter" (the block wants to continue moving left, but keeps getting pushed back a few units), if I press another movement key at the right time, the moving block will slide across the stationary block on it's corresponding side. I know it's my method of getting the blocks unstuck, so any tips would be appreciated.
Here's essentially what I have:
if (App.GetInput().IsKeyDown(sf::Key::Left))
{
if(coll.detectCollision(Sprite, Spr) != true)
{
Sprite.Move(-100 * ElapsedTime, 0);
}
else
{
Sprite.SetPosition((Sprite.GetPosition().x + 3), (Sprite.GetPosition().y));
}
}