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

Show Posts

This section allows you to view all posts made by this member. Note that you can only see posts made in areas you currently have access to.


Messages - Programmy

Pages: [1] 2
1
 
shortened it now, basically what is happening is that I was able to implement SFML in such that the opponent Sprite would follow and go towards the hero, I was able to also make the opponent even face towards the player wherever he goes , all in one Main Cpp file , when I broke the program up and separated the code into each file that's where the problem came up, the opponent sprite moves only in one direction but does not engage the player anymore, Is it because of the reference I put on the ShowOpponent function?


Opponent .H file

class Opponent:public Player
{
public:
        Opponent();
        ~Opponent();
        sf::Sprite& ShowOpponent();

private:
    sf::Sprite enemySprite;
    sf::Texture enemytexture;
    Player player;
    Clock clock;
    sf::Vector2f playerLocation;
    sf::Vector2f m_Position;
};


Opponent Cpp file

#include "Opponent.h"

Opponent::Opponent()
{
        enemytexture.loadFromFile("Opponent.png");
        enemySprite.setTexture(enemytexture);
        enemySprite.setTextureRect(sf::IntRect(0, 0, 50, 50));
        enemySprite.setPosition(800 / 2, 600 / 2);
       
}


Opponent::~Opponent()
{
}
sf::Sprite& Opponent::ShowOpponent() {

        auto dt = clock.dt();

        //this affects the speed of the opponent going towards you
        float m_Speed = 100.0;

        playerLocation = sprite.getPosition();
        m_Position = enemySprite.getPosition();

        float playerX = playerLocation.x;
        float playerY = playerLocation.y;

        if (playerX < m_Position.x){   //left
                m_Position.x = m_Position.x - m_Speed * dt;
                enemySprite.setTextureRect(sf::IntRect(counterWalking * 0.0f, 136.0f, 27.0f, 36.0f));
        }

        if (playerY < m_Position.y){   //up
                m_Position.y = m_Position.y - m_Speed * dt;
                enemySprite.setTextureRect(sf::IntRect(counterWalking * 0.f, 10.0f, 25.0f, 45.0f));
        }

        if (playerX > m_Position.x){   //right
                m_Position.x = m_Position.x + m_Speed * dt;
                enemySprite.setTextureRect(sf::IntRect(counterWalking * 0.0f, 60.0f, 25.0f, 36.0f));
        }
        if (playerY > m_Position.y){   //down
                m_Position.y = m_Position.y + m_Speed * dt;
                enemySprite.setTextureRect(sf::IntRect(counterWalking * 0.0f, 100.0f, 25.0f, 36.0f));
        }
        enemySprite.setPosition(m_Position);
 
        return enemySprite;
}


at Main.cpp here is the code to draw the Hero and Enemy Sprite
 
    window.draw(player.ShowHero());
    window.draw(opponent.ShowOpponent());

 

2
I'm writing a Zelda clone for study, was able to implement a walkcycle and attack cycle in my player sprite but I'm having trouble making the enemy sprite follow and attack
my hero sprite

[main.cpp]

#include <SFML/Graphics.hpp>
#include "Player.h"
#include "Opponent.h"
#include "OpponentAi.h"

int main()
{
       
        sf::RenderWindow window(sf::VideoMode(800, 600), "My window");
       
        enum class state {

                PLAYING,
                GAMEOVER,
                PAUSED


        };
        Player player;
        Opponent opponent;
        Clock clock;
        OpponentAi opponentAi;
        while (window.isOpen())
        {
               
       
                sf::Event event;
                while (window.pollEvent(event))
                {
                       
                        if (event.type == sf::Event::Closed)
                                window.close();



                }

                 player.P_Movement();
                 opponent.ShowOpponent();



                player.ShowHero().setScale(3, 3);
                opponent.ShowOpponent().setScale(3, 3);

                window.clear(sf::Color::Black);

                // draw everything here...
                 window.draw(player.ShowHero());
                 window.draw(opponent.ShowOpponent());
                // end the current frame
                window.display();
        }

        return 0;
}


 


here is the opponent cpp file


#include "Opponent.h"



Opponent::Opponent()
{
        enemytexture.loadFromFile("Opponent.png");
        enemySprite.setTexture(enemytexture);
        enemySprite.setTextureRect(sf::IntRect(0, 0, 50, 50));
        enemySprite.setPosition(800 / 2, 600 / 2);
       
}


Opponent::~Opponent()
{
}
sf::Sprite& Opponent::ShowOpponent() {

        auto dt = clock.dt();

        //this affects the speed of the opponent going towards you
        float m_Speed = 100.0;



        playerLocation = sprite.getPosition();
        m_Position = enemySprite.getPosition();

        float playerX = playerLocation.x;
        float playerY = playerLocation.y;

        if (playerX < m_Position.x)
        {   //left

                enemySprite.setPosition(playerLocation);
                m_Position.x = m_Position.x - m_Speed * dt;
                enemySprite.setTextureRect(sf::IntRect(counterWalking * 0.0f, 136.0f, 27.0f, 36.0f));
        }

        if (playerY < m_Position.y)
        {   //up
               
                m_Position.y = m_Position.y - m_Speed * dt;
                enemySprite.setTextureRect(sf::IntRect(counterWalking * 0.f, 10.0f, 25.0f, 45.0f));
        }

        if (playerX > m_Position.x)
        {   //right
               
                m_Position.x = m_Position.x + m_Speed * dt;
                enemySprite.setTextureRect(sf::IntRect(counterWalking * 0.0f, 60.0f, 25.0f, 36.0f));
        }
        if (playerY > m_Position.y)
        {   //down
               
                m_Position.y = m_Position.y + m_Speed * dt;
                enemySprite.setTextureRect(sf::IntRect(counterWalking * 0.0f, 100.0f, 25.0f, 36.0f));
        }


        enemySprite.setPosition(m_Position);


       


       
        return enemySprite;
}


 

and here is the opponent .h file

#pragma once
#include "Player.h"
#include "Clock.h"
#include <memory>
#include <iostream>

class Opponent:public Player
{
public:
        Opponent();
        ~Opponent();

        sf::Sprite& ShowOpponent();



       

       



private:
       

        sf::Sprite enemySprite;
    sf::Texture enemytexture;

        Player player;
        Clock clock;
        sf::Vector2f playerLocation;
        sf::Vector2f m_Position;


       


       

};


 


here is my hero header file


#pragma once
#include "SFML/Graphics.hpp"
#include "Clock.h"


enum class Dir_Attack {

        STATIC,
        LEFT,
        RIGHT,
        DOWN,
        UP


};


class Player
{
public:
        Player();
        ~Player();
        sf::Sprite& ShowHero();
        void P_Movement();
        void SetAttack();
       

protected:
        sf::Clock clock;
        sf::Time time;
        float dt;
        Dir_Attack d_p_attack;
        float attackSlash;
        float counterWalking;
        float playerMovementSpeed;
        float multiplier;

        sf::Texture texture;
        sf::Sprite sprite;

private:

       

       

};


 

hero cpp file
#include "Player.h"



Player::Player()
{
        texture.loadFromFile("LinkAnimation.png");
        sprite.setTexture(texture);
        sprite.setTextureRect(sf::IntRect(40, 0, 40, 40));
        attackSlash = 3.0f;
        counterWalking = 1.0f;
        playerMovementSpeed = 10.0f;
        multiplier = 30.f;
}


Player::~Player()
{
}
sf::Sprite& Player::ShowHero() {



        return sprite;
}
void Player::P_Movement() {

        dt = clock.restart().asSeconds();

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
        {
                ShowHero().move(0, -playerMovementSpeed * dt * multiplier);
                ShowHero().setTextureRect(sf::IntRect(counterWalking * 40.f, 40.0f * 1.0f, 40.0f, 40.0f));
               
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
        {
                ShowHero().move(0, playerMovementSpeed * dt * multiplier);
                ShowHero().setTextureRect(sf::IntRect(counterWalking * 40.0f, 0.0f, 40.0f, 40.0f));
               
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
        {
                ShowHero().move(-playerMovementSpeed * dt * multiplier , 0);
                ShowHero().setTextureRect(sf::IntRect(counterWalking * 40.0f, 80.0f, 40.0f, 40.0f));
               
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
        {
                ShowHero().move(playerMovementSpeed * dt * multiplier, 0);
                ShowHero().setTextureRect(sf::IntRect(counterWalking * 40.0f, 119.0f, 40.0f, 40.0f));
         
        }
        //
        //this is the crucial syntax to make the
        //sprite move
        counterWalking++;
        if (counterWalking == 8)
        {
                counterWalking = 0;
        }


}
void Player::SetAttack() {

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) && d_p_attack == Dir_Attack::LEFT)
        {
                sprite.setTextureRect(sf::IntRect(attackSlash * 40.0f , 200.0f, 39.0f, 40.0f));
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) && d_p_attack == Dir_Attack::RIGHT)
        {
                sprite.setTextureRect(sf::IntRect(attackSlash * 40.0f, 236.0f, 38.0f, 38.0f));
        }

        if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) && d_p_attack == Dir_Attack::DOWN)
        {
                sprite.setTextureRect(sf::IntRect(attackSlash * 40.0f, 160.0f, 40.0f, 40.0f));
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) && d_p_attack == Dir_Attack::UP)
        {
                sprite.setTextureRect(sf::IntRect( attackSlash * 40.0f, 280.0f, 40.0f, 40.0f));
        }

        attackSlash++;
        if (attackSlash == 6)
        {

                attackSlash = 0;
        }

}



 


3
General / need help assigning variable to shared pointer
« on: December 14, 2018, 03:52:58 am »
I'm using a shared pointer but I'm having trouble using push_back assigning a value to a vector of shared pointers
how do you go about doing it?

void Window::Test1(std::vector<std::shared_ptr<Earth>>* proxy3)
{
   int *a ;
   int b = 10;

   int *a = &b;

   std::vector<std::shared_ptr<Earth>> proxy4;

   proxy3 = &proxy4;

}

4
I see, now it makes sense

5
need help understanding this function,

void Window::Create(){
auto style = (m_isFullscreen ? sf::Style::Fullscreen: sf::Style::Default);
m_window.create({ m_windowSize.x, m_windowSize.y, 32 }, m_windowTitle, style);
}

I understand that the create function is used like this

m_window.create( sf::VideoMode(800, 600), "mywindow", style);

so how come there are three variables in the parameter enclosed with a curly brace?
the string m_windowTitle and style are there, but what is with the first parameters enclosed with the curly brace,

what is the 32 and what is it used for?

here is the rest of the code I condensed from the book


#include "Window.h"



Window::Window()

{

   Setup("test", sf::Vector2u(800,600));
}
Window::Window(const std::string& title,sf::Vector2u size)
{
   Setup(title, size);

}
void Window::Setup(const std::string& title,sf::Vector2u size)
{
   m_isDone = false;
   m_isFullscreen = false;
   m_windowSize = size;
   m_windowTitle = title;
   Create();

}



Window::~Window()
{
}

bool Window::IsDone()
{
   return m_isDone;
}

sf::RenderWindow * Window::GetRenderWindow()
{
   return &m_window;
}

void Window::BeginWindow()

   m_window.clear(sf::Color::Black);
}

void Window::EndWindow()
{
   m_window.display();
}
void Window::Create()
{
   auto style = (m_isFullscreen ? sf::Style::Fullscreen : sf::Style::Default);

   //m_window.create({ m_windowSize.x, m_windowSize.y, 32}, m_windowTitle, style);

   m_window.create( sf::VideoMode(800, 600), "mywindow", style);

}
void Window::Update()
{
   sf::Event event;
   while (m_window.pollEvent(event))
   {
      if (event.type == sf::Event::Closed)
         m_window.close();
   }



}

6
General discussions / Re: Any Zelda clone or hack and slash game on sfml?
« on: November 03, 2018, 03:35:10 am »
I'm looking for something like the hero has a sword and slashes the enemy,like zelda, link to the past, a hack and slash with a top down view, I'm liking  witchblast I'll pick it apart to see how it works :)

7
General discussions / Any Zelda clone or hack and slash game on sfml?
« on: November 02, 2018, 02:48:23 pm »
all I found were on SDL, are there any SFML projects like these out there?, googled around and didn't find any...

8
Graphics / How do you make a sprite follow another sprite?
« on: September 26, 2018, 04:29:55 am »
like in the rpg where if a character goes up the second and third will follow?
my code only does it where the second sprite follows but it lags behind after some distance
and is obviously not the solution...

#include <SFML/Graphics.hpp>
#include <vector>
#include <iostream>


int main()
{
        sf::RenderWindow window(sf::VideoMode(800, 600), "Test");
       

        sf::Texture heroTexture;
        sf::Sprite heroSprite;

        if (!heroTexture.loadFromFile("Eagle.png"))
        {
                std::cout << "Failed to load Eagle" << std::endl;

        }
        heroSprite.setTexture(heroTexture);


        //square snake
        std::vector<sf::Sprite>hero;
        hero.push_back(sf::Sprite(heroSprite));
        hero.push_back(sf::Sprite(heroSprite));
        hero.push_back(sf::Sprite(heroSprite));




        while (window.isOpen())
        {
                sf::Event event;
                while (window.pollEvent(event))
                {
                        if (event.type == sf::Event::Closed)
                                window.close();

                       
                        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
                        {
                                hero[0].move(-10,0);
                        }
                        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
                        {
                                hero[0].move(+10, 0);
                        }
                        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
                        {
                                hero[0].move(0, -10);
                        }
                        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
                        {
                                hero[0].move(0, +10);
                        }
                       

                        /////////////
                        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
                        {
                                hero[1].move(-9, 0);
                        }

                        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
                        {
                                hero[1].move(+9, 0);
                        }
                        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
                        {
                                hero[1].move(0, -9);
                        }
                        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
                        {
                                hero[1].move(0, +9);
                        }

                }

               

               
                window.clear();
                window.draw(hero[0]);
                window.draw(hero[1]);
                window.draw(hero[2]);
                window.display();
        }

        return 0;
}
 

9
Graphics / how to make a sprite bounce across screen
« on: August 08, 2018, 09:16:57 am »

 I'm having problems with implementation, mainly how do you make the sprite change direction and bounce when it hits the boundary I have made "m_bounds", and make it travel diagonally,and have managed to make the first sprite move but sprite 2 is just going through the wall, I'm still learning C++ so
a simple way to do it would be appreciated not very complex implementation :)

Game.h file
#pragma once

#include "Window.h"
#include "World.h"
#include "Snake.h"
#include "Eagle.h"
#include "Airjeti.h"




class Game
{
public:
        Game();
       
        ~Game();
       


        void setterWindow();
        Window* GetWindow();
       




private:
        Window m_window;
        sf::RenderWindow window;
        sf::VertexArray points;
       
        sf::Texture spaceship;
        sf::Sprite sprite;
       
        sf::Texture Airjet;
        sf::Sprite sprite2;

        sf::RectangleShape m_bounds1;
        sf::RectangleShape m_bounds2;
        sf::RectangleShape m_bounds3;
        sf::RectangleShape m_bounds4;

        Eagle eagle;
        World world;
        Airjeti airjeti;
        bool m_bounce;

       
};


 


Game.cpp file

#include "Game.h"
#include <SFML/Graphics.hpp>
#include <iostream>

Game::Game(): window(sf::VideoMode(800, 600), "Test",sf::Style::Default),points(sf::Points,4)
{
       
}
Game::~Game()
{

}
void Game::setterWindow()
{
       
       
        if (!spaceship.loadFromFile("window/spaceship.png"))
        {
                std::cout << "Failed to load" << std::endl;
        }
        sprite.setTexture(spaceship);


        if (!Airjet.loadFromFile("c:window/Eagle.png"))
        {
                std::cout << "Failed to load" << std::endl;
        }
        sprite2.setTexture(Airjet);
       
       
        sf::Vector2u size = Airjet.getSize();/////////////

        sprite2.setOrigin(0.100f,0.100f);

        sf::Vector2f increment(0.4f, 0.4f);
       
        sprite.setOrigin(0.100f, 0.100f);
       
        m_bounds1.setFillColor(sf::Color(150, 0, 0));
        m_bounds1.setOrigin(0.5f, 0.5f);
        m_bounds1.setSize(sf::Vector2f(10, 1000));

        m_bounds2.setFillColor(sf::Color(150, 0, 0));
        m_bounds2.setOrigin(0.5f, 0.5f);
        m_bounds2.setSize(sf::Vector2f(1000, 10));

        m_bounds3.setFillColor(sf::Color(150, 0, 0));
        m_bounds3.setOrigin(10,-590 );
        m_bounds3.setSize(sf::Vector2f(1000, 10));

        m_bounds4.setFillColor(sf::Color(150, 0, 0));
        m_bounds4.setOrigin(-790, 10);
        m_bounds4.setSize(sf::Vector2f(10, 1000));


        sf::Event event;
        while (window.pollEvent(event))
        {
                if (event.type == sf::Event::Closed)
                        window.close();

               
                 
                if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
                {
                        sprite.move(-5, 0);
                }
                 if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
                 {
                        sprite.move(+5, 0);
                 }
                 if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
                 {
                        sprite.move(0, -5);
                }
                 if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
                {
                        sprite.move(0, +5);
                }

        }
       
       
        if (sprite2.getGlobalBounds().intersects(m_bounds3.getGlobalBounds()))
        {
               
               
                sprite2.move(-10, +10);
               
               
        }

        window.clear(sf::Color::White);
        sprite2.setPosition(sprite2.getPosition() + increment);
        window.draw(sprite);
        window.draw(m_bounds1);
        window.draw(m_bounds2);
        window.draw(m_bounds3);
        window.draw(m_bounds4);
        window.draw(sprite2);
        window.display();
       
       
}


Window* Game::GetWindow()
{

        return &m_window;
}



 

10
General / Re: Where is the value for the Snake size? Snake Game
« on: August 04, 2018, 05:34:28 am »
tried fiddling with the numbers on that vector but it only adjusts the position, not the size, 5 of the x and 7 of the y, as an additional note, I tried adjusting m_blocksize from world cpp and all the graphics in the game got larger like the wall, apple and snake, but how is  m_blockSize affecting the Snakeclass? it shows m_Size without a value in Snake class.

11
General / Re: Where is the value for the Snake size? Snake Game
« on: August 03, 2018, 10:10:14 am »
but theres no value indicated at m_snakebody....

12
General / Where is the value for the Snake size? Snake Game
« on: August 02, 2018, 12:37:15 pm »
I'm studying the book SFML Game Development by example and I'm having trouble understanding where the snake class is getting the size value for the Snake, I suspect that it's in the world.cpp and is initialized by m_blockSize=16, not really sure, I take a look at the snake class at the snake.h and there's no value at int m_size, so
what's going on? is it being initialized by the constructor member initialization list at Game.cpp? could anyone explain how the snake is gettting it's size? where is the snake getting the value?

Game.h

#pragma once
#include "Window.h"
#include "World.h"
#include "Snake.h"


class Game {
public:
        Game();
        ~Game();

        void HandleInput();
        void Update();
        void Render();

        sf::Time GetElapsed();
        void RestartClock();

        Window* GetWindow();
private:
        Window m_window;
        sf::Clock m_clock;
        float m_elapsed;

        World m_world;
        Snake m_snake;
       
       
};
 


Game.cpp

#include "Game.h"

Game::Game() :  m_window("Snake", sf::Vector2u(800, 600)), m_snake(m_world.GetBlockSize()), m_world(sf::Vector2u(800, 600))
{
        m_clock.restart();

       
       
        m_elapsed = 0.0f;

       
}

Game::~Game() {}

sf::Time Game::GetElapsed() { return m_clock.getElapsedTime(); }


void Game::RestartClock() { m_elapsed += m_clock.restart().asSeconds(); }


Window* Game::GetWindow(){      return &m_window; }

void Game::HandleInput() {
        // Input handling.
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up) && m_snake.GetPhysicalDirection() != Direction::Down)
       
        {m_snake.SetDirection(Direction::Up);}


        else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)
        && m_snake.GetPhysicalDirection() != Direction::Up) {
                m_snake.SetDirection(Direction::Down);
        }
        else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)
                && m_snake.GetPhysicalDirection() != Direction::Right) {
                m_snake.SetDirection(Direction::Left);
        }
        else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)
                && m_snake.GetPhysicalDirection() != Direction::Left) {
                m_snake.SetDirection(Direction::Right);
        }
}

void Game::Update() {
        m_window.Update();
        float timestep = 1.0f / m_snake.GetSpeed();
        if (m_elapsed >= timestep) {
                m_snake.Tick();
                m_world.Update(m_snake);
                m_elapsed -= timestep;
                if (m_snake.HasLost()) {
                       
                        m_snake.Reset();
                }
        }
}

void Game::Render() {
        m_window.BeginDraw();
        // Render here.
        m_world.Render(*m_window.GetRenderWindow());
        m_snake.Render(*m_window.GetRenderWindow());
       

        m_window.EndDraw();
}

 


World.h

#pragma once
#include <SFML/Graphics.hpp>
#include "Snake.h"

class World {
public:
        World(sf::Vector2u l_windSize);
        ~World();

        int GetBlockSize();

        void RespawnApple();

        void Update(Snake& l_player);
        void Render(sf::RenderWindow& l_window);
private:
        sf::Vector2u m_windowSize;
        sf::Vector2i m_item;
        int m_blockSize;

        sf::CircleShape m_appleShape;
        sf::RectangleShape m_bounds[4];
};

 

World.cpp

#include "World.h"

World::World(sf::Vector2u l_windSize) {
        m_blockSize = 16;

        m_windowSize = l_windSize;
        RespawnApple();
        m_appleShape.setFillColor(sf::Color::Red);
        m_appleShape.setRadius(m_blockSize / 2);

        for (int i = 0; i < 4; ++i) {
                m_bounds[i].setFillColor(sf::Color(150, 0, 0));
                if (!((i + 1) % 2)) {
                        m_bounds[i].setSize(sf::Vector2f(m_windowSize.x, m_blockSize));
                }
                else {
                        m_bounds[i].setSize(sf::Vector2f(m_blockSize, m_windowSize.y));
                }
                if (i < 2) {
                        m_bounds[i].setPosition(0, 0);
                }
                else {
                        m_bounds[i].setOrigin(m_bounds[i].getSize());
                        m_bounds[i].setPosition(sf::Vector2f(m_windowSize));
                }
        }
}

World::~World() {}

int World::GetBlockSize() { return m_blockSize; }

void World::RespawnApple() {
        int maxX = (m_windowSize.x / m_blockSize) - 2;
        int maxY = (m_windowSize.y / m_blockSize) - 2;
        m_item = sf::Vector2i(
                rand() % maxX + 1, rand() % maxY + 1);
        m_appleShape.setPosition(
                m_item.x * m_blockSize,
                m_item.y * m_blockSize);
}

void World::Update(Snake& l_player) {
        if (l_player.GetPosition() == m_item) {
                l_player.Extend();
                l_player.IncreaseScore();
                RespawnApple();
        }

        int gridSize_x = m_windowSize.x / m_blockSize;
        int gridSize_y = m_windowSize.y / m_blockSize;

        if (l_player.GetPosition().x <= 0 ||
                l_player.GetPosition().y <= 0 ||
                l_player.GetPosition().x >= gridSize_x - 1 ||
                l_player.GetPosition().y >= gridSize_y - 1)
        {
                l_player.Lose();
        }
}

void World::Render(sf::RenderWindow& l_window) {
        for (int i = 0; i < 4; ++i) {
                l_window.draw(m_bounds[i]);
        }
        l_window.draw(m_appleShape);
}
 

Snake.h

#pragma once
#include <SFML/Graphics.hpp>

#include <vector>

struct SnakeSegment
{
        SnakeSegment(int x, int y) : position(x, y)

        {

        }
        sf::Vector2i position;
};

using SnakeContainer = std::vector<SnakeSegment>;

enum class Direction { None, Up, Down, Left, Right };

class Snake {
public:
        Snake(int l_blockSize);
        ~Snake();

        // Helper methods.
        void SetDirection(Direction l_dir);
        Direction GetDirection();
        int GetSpeed();
        sf::Vector2i GetPosition();
        int GetLives();
        int GetScore();
        void IncreaseScore();
        bool HasLost();

        void Lose(); // Handle losing here.
        void ToggleLost();

        Direction GetPhysicalDirection();

        void Extend(); // Grow the snake.
        void Reset(); // Reset to starting position.

        void Move(); // Movement method.
        void Tick(); // Update method.
        void Cut(int l_segments); // Method for cutting snake.
        void Render(sf::RenderWindow& l_window);
private:
        void CheckCollision(); // Checking collisions.

        SnakeContainer m_snakeBody; // Segment vector.
        int m_size; // Size of the graphics.
        Direction m_dir; // Current direction.
        int m_speed; // Speed of the snake.
        int m_lives; // Lives.
        int m_score; // Score.
        bool m_lost; // Losing state.
        sf::RectangleShape m_bodyRect; // Shape used in rendering.
       
};
 

Snake.cpp

#include "Snake.h"

Snake::Snake(int l_blockSize) {

        m_size = l_blockSize;   m_bodyRect.setSize(sf::Vector2f(m_size -1 , m_size -1 ));
        Reset();
}

Snake::~Snake() {}

void Snake::SetDirection(Direction l_dir) { m_dir = l_dir; }
Direction Snake::GetDirection() { return m_dir; }
int Snake::GetSpeed() { return m_speed; }
sf::Vector2i Snake::GetPosition() {
        return (!m_snakeBody.empty() ? m_snakeBody.front().position : sf::Vector2i(1, 1));
}

int Snake::GetLives() { return m_lives; }
int Snake::GetScore() { return m_score; }

void Snake::IncreaseScore() {m_score += 10;}
bool Snake::HasLost() { return m_lost; }
void Snake::Lose() { m_lost = true; }
void Snake::ToggleLost() { m_lost = !m_lost; }

Direction Snake::GetPhysicalDirection() {
        if (m_snakeBody.size() <= 1) {
                return Direction::None;
        }

        SnakeSegment& head = m_snakeBody[0];
        SnakeSegment& neck = m_snakeBody[1];

        if (head.position.x == neck.position.x) {
                return (head.position.y > neck.position.y
                        ? Direction::Down : Direction::Up);
        }
        else if (head.position.y == neck.position.y) {
                return (head.position.x > neck.position.x
                        ? Direction::Right : Direction::Left);
        }

        return Direction::None;
}

void Snake::Extend() {
        if (m_snakeBody.empty()) { return; }
        SnakeSegment& tail_head =
                m_snakeBody[m_snakeBody.size() - 1];

        if (m_snakeBody.size() > 1)
        {
                SnakeSegment& tail_bone =
                        m_snakeBody[m_snakeBody.size() - 2];

                if (tail_head.position.x == tail_bone.position.x)
                {
                        if (tail_head.position.y > tail_bone.position.y)
                        {
                                m_snakeBody.push_back(SnakeSegment(
                                        tail_head.position.x, tail_head.position.y + 1));
                        }
                        else
                        {
                                m_snakeBody.push_back(SnakeSegment(
                                        tail_head.position.x, tail_head.position.y - 1));
                        }
                }
                else if (tail_head.position.y == tail_bone.position.y)
                {
                        if (tail_head.position.x > tail_bone.position.x)
                        {
                                m_snakeBody.push_back(SnakeSegment(
                                        tail_head.position.x + 1, tail_head.position.y));
                        }
                        else
                        {
                                m_snakeBody.push_back(SnakeSegment(
                                        tail_head.position.x - 1, tail_head.position.y));
                        }
                }
        }
        else
        {
                if (m_dir == Direction::Up)
                {
                        m_snakeBody.push_back(SnakeSegment(
                                tail_head.position.x, tail_head.position.y + 1));
                }
                else if (m_dir == Direction::Down) {
                        m_snakeBody.push_back(SnakeSegment(
                                tail_head.position.x, tail_head.position.y - 1));
                }
                else if (m_dir == Direction::Left) {
                        m_snakeBody.push_back(SnakeSegment(
                                tail_head.position.x + 1, tail_head.position.y));
                }
                else if (m_dir == Direction::Right) {
                        m_snakeBody.push_back(SnakeSegment(
                                tail_head.position.x - 1, tail_head.position.y));
                }
        }
}

void Snake::Reset() {
        m_snakeBody.clear();
        m_snakeBody.push_back(SnakeSegment(5, 7));
        m_snakeBody.push_back(SnakeSegment(5, 6));
        m_snakeBody.push_back(SnakeSegment(5, 5));

        SetDirection(Direction::None); // Start off still.
        m_speed = 15;
        m_lives = 3;
        m_score = 0;
        m_lost = false;
}

void Snake::CheckCollision() {
        if (m_snakeBody.size() < 5) { return; }
        SnakeSegment& head = m_snakeBody.front();
        for (auto itr = m_snakeBody.begin() + 1;
                itr != m_snakeBody.end(); ++itr)
        {
                if (itr->position == head.position) {
                        int segments = m_snakeBody.end() - itr;
                        Cut(segments);
                        break;
                }
        }
}

void Snake::Move()
{
    for (int i = m_snakeBody.size() - 1; i > 0; --i) {m_snakeBody[i].position = m_snakeBody[i - 1].position;}
       
        if (m_dir == Direction::Left) {--m_snakeBody[0].position.x;}
       
        else if (m_dir == Direction::Right) {++m_snakeBody[0].position.x;}
       
        else if (m_dir == Direction::Up) {--m_snakeBody[0].position.y;}
       
        else if (m_dir == Direction::Down) {++m_snakeBody[0].position.y;}  
}

void Snake::Tick() {
        if (m_snakeBody.empty()) { return; }
        if (m_dir == Direction::None) { return; }
        Move();
        CheckCollision();
}

void Snake::Cut(int l_segments) {
        for (int i = 0; i < l_segments; ++i) {
                m_snakeBody.pop_back();
        }
        --m_lives;
        if (!m_lives) { Lose(); return; }


}

void Snake::Render(sf::RenderWindow& l_window) {
        if (m_snakeBody.empty()) { return; }

        auto head = m_snakeBody.begin();
        m_bodyRect.setFillColor(sf::Color::Yellow);
        m_bodyRect.setPosition(head->position.x * m_size,
                head->position.y * m_size);
        l_window.draw(m_bodyRect);

        m_bodyRect.setFillColor(sf::Color::Green);
        for (auto itr = m_snakeBody.begin() + 1;
                itr != m_snakeBody.end(); ++itr) {
                m_bodyRect.setPosition(itr->position.x * m_size,
                        itr->position.y * m_size);
                l_window.draw(m_bodyRect);
        }
}
 

13
this helps a lot, thanks for the thorough explanation :)

14
Graphics / How to make the sprite move when pushed by another sprite
« on: June 16, 2018, 07:45:22 am »
I'm having  a hard time making a sprite move when pushed, basically
it moves left all the time regardless of the code that I put in
basically I want the sprite to move left when pushed left, right when right
up when up and down when down

I'm getting
confused to where the  x an y coordinates are, I think -x is right +x left
and + y is up and -y is down or I may be wrong, need help


#include <SFML/Graphics.hpp>
#include <iostream>



void main(int argc, char** argv[]) {



        sf::RenderWindow window;
        window.create(sf::VideoMode(800, 600), "test", sf::Style::Default);

        sf::Texture texture;
        texture.loadFromFile("c:/Users/jason/source/repos/SFML2/Eagle.png");
        sf::Sprite sprite(texture);
        sf::Sprite sprite2(texture);

        sf::Vector2u size = texture.getSize();
        sprite.setOrigin(size.x / 2, size.y / 2);


        sf::Vector2f increment(0.4f, 0.4f);


        sprite.setTexture(texture);
        sprite.setPosition(sf::Vector2f(0, 250));

        sprite2.setTexture(texture);
        sprite2.setOrigin(-200, -200);


        while (window.isOpen())
        {

                sf::Event event;
                while (window.pollEvent(event))
                {
                        if (event.type == sf::Event::Closed)
                                window.close();

                        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
                        {
                                sprite.move(-5, 0);
                        }
                        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
                        {
                                sprite.move(+5, 0);
                        }
                        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up))
                        {
                                sprite.move(0, -5);
                        }
                        if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down))
                        {
                                sprite.move(0, +5);
                        }              
                       
                       
                        if (sprite.getGlobalBounds().intersects(sprite2.getGlobalBounds()))
                        {
                                if (sprite.getPosition().x > sprite2.getPosition().x)
                                        sprite2.move(+10, 0);  
                        }
                       
                }

                window.clear(sf::Color(255, 255, 255));
                window.draw(sprite);
                window.draw(sprite2);
                window.display();
        }


}


 

15
oh nevermind I fixed it.....I made a time object beforehand, how silly of me

Pages: [1] 2
anything