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

Author Topic: Vector in SFML  (Read 3031 times)

0 Members and 1 Guest are viewing this topic.

Feldscher

  • Newbie
  • *
  • Posts: 1
    • View Profile
Vector in SFML
« on: December 31, 2018, 02:41:45 pm »
Hello there!
Im starting to learn SFML and are playing with some basic drawables atm.
Im trying to programm a simple Snake game, with sf::Rectangles as the body segments.

Everything is working fine (Moving the Head-Segment, border and segment collision check and creating new Segments...)
BUT im not able to reset the position of existing segments to follow the Head.. They just dont save the given positions...

Normally, the actual position should become the "old" position and then the actual position gets updated by the old position of the segment in front of it...


void Game::update_game()
{
    // Neues Item zum aufsammeln generieren
    if (ptrItem == NULL)
    {
        ptrItem = new Food;
    }


    // Spieler um increment bewegen
    Head.set_last_position();   // Bisherige Position speichern
    increment_Spieler = window.get_increment_Spieler();
    Head.set_new_position(sf::Vector2f(Head.get_position().x + increment_Spieler.x, Head.get_position().y + increment_Spieler.y));


    if (Body.size() == 1)
    {
        Body[0].set_last_position();
        Body[0].set_new_position(Head.get_last_position());
    }

    if (Body.size() >= 2)
    {
        for(int i = 1; i < Body.size(); i++)
        {
            Body[i].set_last_position();
            Body[i].set_new_position(Body[i-1].get_last_position());
        }
    }

    // Testen ob Item eingesammelt, wenn ja Items neue Position zuweisen und Schlangenkörper verlängern
    if (Head.segment.getGlobalBounds().intersects(ptrItem->target.getGlobalBounds()))
    {
        ptrItem->set_new_target();

        if (Body.size() == 0)
        {
            Body.push_back(Snakesegment(Head.get_last_position()));
        }

        if (Body.size() >= 1)   // Wenn mindestens ein Element vorhanden
        {
            Body.push_back(Snakesegment(Body[Body.size()-1].get_last_position()));  // Neues Element hinten an vorherige Position des bis dahin letzten Elements hängen
        }
    }
 


A hint why this doesnt work?

Geheim

  • Full Member
  • ***
  • Posts: 201
    • View Profile
    • Email
Re: Vector in SFML
« Reply #1 on: January 01, 2019, 11:03:51 am »
Without knowing anything about how your set and get functions work, look again at your if statement where the Body is at least 2 in size. What happens to Body[0] ?

They just dont save the given positions...
Do they save nothing at all? Then it most likely has to do with your set and get functions.

Also, does the snake really move the way you think? Maybe think again, in slow motion ;)
Failing to succeed does not mean failing to progress!