My problem is that in the:
if(Keyboard::isKeyPressed(Keyboard::D))
{
source.y=right;
source.x++;
}
fragment of my simple code, the source.y doesn't want to take the value of 0. What's causing this?
Full code:
#include <SFML/Graphics.hpp>
#include <iostream>
#include <conio.h>
#include <windows.h>
#define CW 64//cell width
using namespace std;
using namespace sf;
int main()
{
RenderWindow win(VideoMode(1200,800),"lol");
win.setFramerateLimit(30);
Texture t;
t.loadFromFile("char.png");
Sprite char_;
char_.setTexture(t);
enum dir{right,left,idle};
Vector2i source(1,idle);
while(win.isOpen())
{
win.clear();
if(Keyboard::isKeyPressed(Keyboard::D))
{
source.y=right;
source.x++;
}
if(Keyboard::isKeyPressed(Keyboard::A))
{
source.y=left;
source.x++;
}
else
{
source.y=idle;
}
char_.setTextureRect(IntRect(source.x*CW,source.y*CW,CW,CW));
if(source.x==3 || source.x>3)
{
source.x=0;
}
cout<<"source.x: "<<source.x<<endl;
cout<<"source.y: "<<source.y<<endl;
win.draw(char_);
win.display();
system("cls");
}
}
You are missing an else after your first if:
if(Keyboard::isKeyPressed(Keyboard::D))
{
source.y=right;
source.x++;
}
if(Keyboard::isKeyPressed(Keyboard::A))
{
source.y=left;
source.x++;
}
else
{
source.y=idle;
}
Even if D is pressed, you will end up in the final else clause, because it's not A. So source.y will take the value of right, but will immediately be overwritten by the line source.y=idle;
What you probably want (check the else in front of the second if) is:
if(Keyboard::isKeyPressed(Keyboard::D))
{
source.y=right;
source.x++;
}
else if(Keyboard::isKeyPressed(Keyboard::A))
{
source.y=left;
source.x++;
}
else
{
source.y=idle;
}
Related
I recently started working on SFML. I just created a window then later started to separating my main code. First i wrote a window class.
Nothing special, just draws my window and prints mouse coordinates.
#include "Window.hpp"
#include <iostream>
Window::Window()
{
SetWindow(800,600, "JUST SFML");
}
void Window::SetWindow(unsigned int width, unsigned int height, sf::String title)
{
m_sfmlWindow.create(sf::VideoMode(width, height), title);
}
void Window::StartDrawing()
{
m_sfmlWindow.clear();
}
void Window::EndDrawing()
{
m_sfmlWindow.display();
}
bool Window::isClosed()
{
return !m_sfmlWindow.isOpen();
}
void Window::EventControl()
{
sf::Event event;
while (m_sfmlWindow.pollEvent(event))
{
if (event.type == sf::Event::Closed)
{
m_sfmlWindow.close();
}
if (event.type == sf::Event::MouseMoved)
{
std::cout << event.mouseMove.x << " , " << event.mouseMove.y << std::endl;
}
}
}
void Window::Draw(sf::Drawable& shape)
{
m_sfmlWindow.draw(shape);
}
Everything worked perfectly.
Then i tought i need a GameManager class that i can just use in my main class.
#include "GameManager.hpp"
GameManager::GameManager()
{
m_shape.setRadius(30.0f);
m_shape.setFillColor(sf::Color::Magenta);
m_incVal = 1.0f;
m_posX = 10.0f;
m_frameRate = 1.0f / 60.0f;
}
GameManager::~GameManager()
{
}
void GameManager::InputControl()
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right))
{
m_incVal = 1.0f;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left))
{
m_incVal = -1.0f;
}
}
void GameManager::UpdateScene()
{
if (m_deltaTime.asSeconds() >= m_frameRate)
{
m_posX += m_incVal;
m_shape.setPosition(m_posX, 300);
m_deltaTime -= sf::seconds(m_frameRate);
}
}
void GameManager::DrawScene()
{
m_window.StartDrawing();
m_window.Draw(m_shape);
m_window.EndDrawing();
}
void GameManager::RestartClock()
{
m_deltaTime += m_clock.restart();
}
bool GameManager::isFinished()
{
return m_window.isClosed();
}
It was perfectly working when i use window object, later i've changed to gamemanager it start being not responding.. I can get keyboard inputs but not mouse move coordinates. Where am i make it wrong?
#include <SFML/Graphics.hpp>
#include "GameManager.hpp"
#include "Window.hpp"
int main()
{
GameManager gameManager;
while (!gameManager.isFinished())
{
gameManager.InputControl();
gameManager.UpdateScene();
gameManager.DrawScene();
gameManager.RestartClock();
}
/*
sf::CircleShape shape(100.0f);
shape.setFillColor(sf::Color::Magenta);
shape.setOutlineThickness(5.0f);
shape.setOutlineColor(sf::Color::White);
Window window;
while (!window.isClosed())
{
window.EventControl();
window.StartDrawing();
window.Draw(shape);
window.EndDrawing();
}
*/
return 0;
}
In order to receive events (such as the mouse moving), you need to call pollEvents on the window.
In your commented code, you were doing this through your Window::EventControl() method. Your new GameManager class isn't calling this, however, so you aren't receiving any events.
So I just started learning SFML. So, I want to take an input x. And when x=1 the color of the rectangle that I created changes. Here is my code:
#include <SFML/Graphics.hpp>
#include <iostream>
using namespace std;
int main()
{
int x;
sf::RenderWindow MW(sf::VideoMode(1200, 650), "Dominus", sf::Style::Close |
sf::Style::Titlebar);
sf::RectangleShape bg(sf::Vector2f(1200.0f, 650.0f)); bg.setFillColor(sf::Color::Green);
while (MW.isOpen()) {
sf::Event evnt;
while (MW.pollEvent(evnt)) {
switch (evnt.type) {
case sf::Event::Closed:
MW.close(); break;
}
}
cin >> x;
if (x == 1) {
bg.setFillColor(sf::Color::Blue);
}
MW.clear();
MW.draw(bg);
MW.display();
}
return 0;
}
Now the problem here that I am facing is that the window does not load properly. And when I move the 'cin' out of the loop, I can't seem to take an input at all.
You can use threads:
#include <SFML/Graphics.hpp>
#include <iostream>
#include <mutex>
#include <thread>
int main() {
std::mutex xmutex;
int x = 0;
std::thread thr([&]() {
std::lock_guard<std::mutex> lock(xmutex);
int x;
std::cin >> x;
});
thr.detach();
sf::RenderWindow MW(sf::VideoMode(1200, 650), "Dominus", sf::Style::Close | sf::Style::Titlebar);
sf::RectangleShape bg(sf::Vector2f(1200.0f, 650.0f)); bg.setFillColor(sf::Color::Green);
while (MW.isOpen()) {
sf::Event evnt;
while (MW.pollEvent(evnt)) {
switch (evnt.type) {
case sf::Event::Closed:
MW.close(); break;
}
}
{
std::lock_guard<std::mutex> lock(xmutex);
if (x == 1) {
bg.setFillColor(sf::Color::Blue);
}
}
MW.clear();
MW.draw(bg);
MW.display();
}
}
I was making a simple snake game but when I tried moving a part of my snake
it went to 0,0.
I keep all parts of my snake inside a vector.
But when I do something like
vector[0].getPosition()
//(In my code: snakeParts[0].getPosition())
It just returns 0,0.
I also don't get any error whilst compiling.
Here's my code:
#include <SFML/Graphics.hpp>
#include <iostream>
#include <string>
#include <unistd.h>
#include <vector>
using namespace std;
sf::RenderWindow App(sf::VideoMode(854, 480), "Snake");
sf::RectangleShape snake;
sf::RectangleShape snake2;
vector<sf::RectangleShape> snakeParts;
string movingDirection = "Right";
int updatePos() {
snakeParts[1].setPosition(snakeParts[0].getPosition()); //Where my problem lies
if (movingDirection == "Left") {
snake.move(-32,0);
}
else if (movingDirection == "Right") {
snake.move(32,0);
}
else if (movingDirection == "Up") {
snake.move(0,-32);
}
else if (movingDirection == "Down") {
snake.move(0,32);
}
//for (int i=0; i<snakeParts.size(); i++) {
//int target = snakeParts.size()-i;
}
int main()
{
snake.setSize(sf::Vector2f(32, 32));
snake.setFillColor(sf::Color::Green);
snake2.setSize(sf::Vector2f(32, 32));
snake2.setFillColor(sf::Color::Red);
snakeParts.push_back(snake);
snakeParts.push_back(snake2);
while (App.isOpen())
{
sf::Event event;
while (App.pollEvent(event))
{
if (event.type == sf::Event::Closed)
App.close();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
movingDirection = "Left";
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
movingDirection = "Right";
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
movingDirection = "Down";
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
movingDirection = "Up";
}
}
usleep(100000);
//cout << movingDirection << endl;
updatePos();
App.clear();
App.draw(snake);
App.draw(snake2);
App.display();
}
return 0;
}
I think it's something to do with pointers?
But I wouldn't know how I would fix that...
Dump those global snakeN variables! Are you going to declare everything up to snake100 if you want to have 100 cells? Your vector is storing copies (those are left untouched on (0, 0)), on which you should be performing all the logic.
Make all other global variables local to a function or member of a class and use function parameters where needed.
movingDirection should be an enum.
updatePos with its current signature should return something.
I am trying to make a bar for each object of the class test. There's a private variable, status. If the value of status == 0 the bar changes color to red else it changes color to green. After multiple inputs from the for loop, the graphics window of the program crashes. Please assist me where am I doing wrong?
/* bar example */
#include <iostream>
#include <graphics.h>
using namespace std;
#include <stdlib.h>
#include <stdio.h>
#include <conio.h>
class test
{
private:
int x;
public:
test()
{
}
int getX()
{
if(x==0)
{
cout << "Room Empty";
}
else
if (x==1)
{
cout << "Room Occupied";
}
return x;
}
void setX(int check)
{
x=check;
this->update();
}
void update()
{
//Block to change the colour of the bar on the screen
if(x==0)
{
setfillstyle(INTERLEAVE_FILL,RED);
bar(100,100,20,20);
}
else
if(x==1)
{
setfillstyle(INTERLEAVE_FILL,BLUE);
bar(100,100,20,20);
}
}
};
int main(void)
{
/* request autodetection */
int gdriver = DETECT, gmode, errorcode;
int midx, midy, i;
/* initialize graphics and local variables */
initgraph(&gdriver, &gmode, "");
/* read result of initialization */
errorcode = graphresult();
if (errorcode != grOk) { /* an error occurred */
printf("Graphics error: %s\n", grapherrormsg(errorcode));
printf("Press any key to halt:");
getch();
exit(0); /* terminate with an error code */
}
int x;
test object;
for(int i=0;i<20;i++)
{
cout << "Enter 0 for red, 1 for Blue: ";
cin >> x;
object.setX(x);
}
//getch();
/* clean up */
closegraph();
return 0;
}
Hello I add Text Class to my project , where text is fallowing the moving ball
i build is successful, but when i trying debuging i receive
Unhandled exception at 0x0F58155F (sfml-graphics-d-2.dll) in Lotto.exe: 0xC0000005: Access violation reading location 0xCCCCCD24.
My main.cpp
#include <iostream>
#include <SFML/Graphics.hpp>
#include "Ball.h"
#include "Line.h"
#include "TextBall.h"
using namespace std;
using namespace sf;
int main()
{
RenderWindow win(VideoMode(800, 600), L"RozdziaĆ 1");
Clock stoper;
Font font;
font.loadFromFile("arial.ttf");
float ySpeed = -100;
float xSpeed = -100;
Ball CircleOne(win);
Line linia1(win);
linia1.sie(500, 500);
linia1.position(20, 20);
linia1.thiness(2);
TextBall text(win);
text.dFont(font);
text.dString("Hello");
text.dCharacterSize(40);
text.dColor(sf::Color::Black);
text.dPosition(CircleOne.GetPosition().x + 5, CircleOne.GetPosition().y);
CircleOne.SetPozition(100, 100);
// CircleOne.SetOutlineColor(Color::Red);
CircleOne.Fil(Color::Yellow);
CircleOne.Promien(15);
// CircleOne.thinesS();
while (win.isOpen())
{
win.clear(Color::White);
Event e;
while (win.pollEvent(e))
{
if (e.type == Event::Closed)
win.close();
}
auto dt = stoper.restart().asSeconds();
CircleOne.Move(xSpeed *dt , ySpeed * dt);
//text.Move(xSpeed *dt, ySpeed * dt);
linia1.draw();
CircleOne.Draw();
text.Draw();
int positionY = CircleOne.GetPosition().y;
if (positionY <= 0){ ySpeed = -ySpeed; }
if (positionY >= 600.0-2*CircleOne.radius()){ ySpeed = -ySpeed; }
int positionX = CircleOne.GetPosition().x;
if (positionX <= 0){ xSpeed = -xSpeed; }
if (positionX >= 800.0-2*CircleOne.radius()){xSpeed = -xSpeed; }
win.display();
}
}
and TextBall class
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <iostream>
using namespace std;
using namespace sf;
class TextBall{
public:
TextBall(RenderWindow&);
void dString(String);
void dCharacterSize(int);
void dColor(Color);
void dPosition(float, float);
void Move(float, float);
void Draw();
void dFont(Font);
private:
Text text;
RenderWindow& Render;
};
TextBall::TextBall(sf::RenderWindow& app) : Render(app)
{
}
void TextBall::dString(String liczba)
{
text.setString(liczba);
}
void TextBall::dCharacterSize(int size)
{
text.setCharacterSize(size);
}
void TextBall::dColor(Color kolor)
{
text.setColor(kolor);
}
void TextBall::dPosition(float x, float y)
{
text.setPosition(x, y);
}
void TextBall::Move(float a, float b)
{
text.move(a, b);
}
void TextBall::Draw()
{
Render.draw(text);
}
void TextBall::dFont(Font fon)
{
text.setFont(fon);
}
When i add text without a additional class its working fine, i afraid it object sending in TextBall is faulty. Plaese how can i solve this project