Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Jumping Rectangle???  (Read 1381 times)

0 Members and 1 Guest are viewing this topic.

Hazique35

  • Newbie
  • *
  • Posts: 16
    • View Profile
Jumping Rectangle???
« on: April 10, 2013, 10:36:16 pm »
Hello. I have been able to make a rectangle to move, but I cannot make it jump. Is there a certain way of doind this? I tried using a for loop, but that didnt work... Here is a snippet of my full code:

else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
{
        int paramX = 0;
        int paramY = -10;
        sf::Vector2f pos = rectangle.getPosition();
        rectangle.setPosition(pos.x + paramX, pos.y + paramY);
}

I need a couple of hints. Hopefully I will only need a bit of help.
Thanks

massive_potato

  • Newbie
  • *
  • Posts: 37
    • View Profile
Re: Jumping Rectangle???
« Reply #1 on: April 10, 2013, 11:57:16 pm »
One thing you could do is have a velocity associated with your rectangle. When you press the up key, you could change the velocity's y-value to a negative value (moving up). Then, you can increase the velocity's y-value each frame (to simulate gravity). In code:

// Set up code
//...
// Relevant code
sf::Vector2f velocity(0.f, 0.f); // Positive x = move right, negative y = move up (relative to screen)
sf::Clock timer;
while (someCondition) // Game loop
{
    float timePassed = timer.getElapsedTime().asSeconds();
    if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) // On key press, change velocity
    {
        velocity = sf::Vector2f(velocity.x, -100.f);
    }
    velocity.y += 9.8f * timePassed;
    rect.move(velocity * timePassed);
    // Do whatever else you need to do
    // ...
}
 

Hopefully this is enough to at least get you started.
« Last Edit: April 11, 2013, 12:00:23 am by massive_potato »

Hazique35

  • Newbie
  • *
  • Posts: 16
    • View Profile
Re: Jumping Rectangle???
« Reply #2 on: April 11, 2013, 12:31:40 am »
thanks, ill probably be able to figure it out now.