Is it possible to create an car object in sfml that consists of a parallelogram, a rectangle, and two wheels? - sfml

I created a car in c++ and sfml:
And here is how:
#include <iostream>
#include <SFML/Graphics.hpp>
#include <SFML/Audio.hpp>
using namespace std;
using namespace sf;
int main()
{
RenderWindow window(VideoMode(1500, 600), "SFML Window", Style::Default);
window.setVerticalSyncEnabled(true);
cout << "haha" << endl;
VertexArray curve(LinesStrip);
for (int x = 0; x <= 1500; x+=50)
{
curve.append(Vertex(Vector2f(x, 300 - cos(x)*200)));
}
ConvexShape carRoof;
RectangleShape carBody;
CircleShape backWheel, frontWheel;
carRoof.setPointCount(4);
carRoof.setOutlineThickness(4);
carRoof.setPoint(0, Vector2f(38, 55));
carRoof.setPoint(1, Vector2f(50, 45));
carRoof.setPoint(2, Vector2f(80, 45));
carRoof.setPoint(3, Vector2f(92, 55));
carRoof.setOrigin(0, 0);
carRoof.setFillColor(Color::Black);
carRoof.setPosition(0, -4.0f);
carBody.setOutlineThickness(4);
carBody.setSize(Vector2f(90, 14));
carBody.setPosition(20, 58.5);
carBody.setFillColor(Color::Black);
backWheel.setRadius(8);
backWheel.setPointCount(100);
backWheel.setPosition(35, 75);
backWheel.setOrigin(4, 4);
backWheel.setOutlineThickness(4);
backWheel.setFillColor(sf::Color::Black);
frontWheel.setRadius(8);
frontWheel.setPointCount(100);
frontWheel.setPosition(80, 75);
frontWheel.setOrigin(4, 4);
frontWheel.setOutlineThickness(4);
frontWheel.setFillColor(sf::Color::Black);
Event event;
while (window.isOpen())
{
while(window.pollEvent(event))
{
if (event.type == Event::Closed)
{
window.close();
}
}
window.clear();
window.draw(curve);
window.draw(carRoof);
window.draw(carBody);
window.draw(backWheel);
window.draw(frontWheel);
window.display();
}
return 0;
}
I am wondering how can I create a class Car such that these 4 object are combined into one, so that it can have even it's own move function like the individual shapes, and also it should be drawable. I have spent a few days trying to tackle this out but to no avail.

You can create a Car class that inherits sf::Drawable and overloads the draw() function. Then you can add your custom functions like move() and anything that you could expect from a car. This way you can instantiate as many Cars as you want and draw them like you would with any other SFML shape.
Here's the documentation for sf::Drawable.

Related

SFML Touch position is not correct

I am testing a touch in sfml on android using app called cxx droid. My code set's the RectangleShape where i press. But even when i make the position relative to window its not relative to it. I touch in place shape's pos in another place!
My Code :
#include <iostream>
#include <SFML/Graphics.hpp>
using namespace std;
using namespace sf;
Font font;
int main() {
font.loadFromFile("font.otf");
RenderWindow window(VideoMode(500,700),"My window",Style::Titlebar | Style::Close);
window.setFramerateLimit(60);
RectangleShape shape(Vector2f(300,40));
while(window.isOpen()) {
window.setView(window.getDefaultView());
Event event;
while(window.pollEvent(event)) {
if(event.type == event.Closed) {
window.close();
}
}
if(Touch::isDown(0)) {
shape.setPosition(Touch::getPosition(0,window).x,Touch::getPosition(0,window).y);
}
window.clear(Color::Green);
window.draw(shape);
window.display();
}
return 0;
}
If the top left corner of the shape is at the position you touch on screen then it is correct but you need to set the origin of the shape to the center of the shape.
a few weeks i had the samd problem
Your Rectangle needs a FloatRect
sf::FloatRect shapeRect = shape.getGlobalBounds;
Then you have to use mapPixelToCoords in the while(window.isOpen()); loop
sf::Vector2i pixelPos = sf::Touch::getPosition(0, window);
sf::Vector2f worldPos = window.mapPixelToCoords(pixelPos);
Then you use both things with contains
if(shapeRect.contains(worlPos))
{
// type your stuff in
}
Now the Touch have to work only in the Shape, hope this help you

SFML Sprite isn't showing on the window even though it isn't giving me any errors

I'm working with a ref class and using SFML for the graphics, so at the beginning the problem I encounter was facing non-managed members in a managed class, I fixed that problem but now, I'm unable to see the sprite in the window i'm working
#include <SFML/Graphics.hpp>
#pragma make_public(sf::Sprite)
using namespace sf;
using namespace System::Collections::Generic;
namespace GameModel {
public ref class Grass {
public:
Sprite* Sprite;
Texture* Texture;
int Size;
Grass(int size) {
Size = size;
Texture = new sf::Texture();
Sprite = new sf::Sprite(*Texture);
Texture->loadFromFile("Imagenes/Grass.png");
//Image is 500x500px
Sprite->setTexture(*Texture,true);
Sprite->setScale(float(Size / 500), float(Size / 500));
}
void Draw(sf::RenderTarget& rt) {
rt.draw(*Sprite);
}
void Move(float x, float y) {
Sprite->setPosition(x, y);
}
};
public ref class Garden {
public:
List <Grass^>^ Grass;
Garden() {
Grass = gcnew List<GameModel::Grass^>();
}
};
}
using namespace GameModel;
int main(){
sf::RenderWindow window(sf::VideoMode(800, 800), "SFML works!");
Grass^ T = gcnew Grass(25);
T->Move(25, 0);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
window.clear();
T->Draw(window);
window.display();
}
return 0;
}
Your render window should be drawing your sprites, not the opposite.
This should work :
window.draw(T);
I fixed the problem, turns out the function setScale wasn't really working, so I changed the member:
int Size;// I changed this
float Size;// for this
after that the function work just fine and the project work as it should

C++ and SFML, no instance of the overloaded function "sf::RenderWindow.draw()" matches the argument list

I am currently trying to make a simple pong game with SFML in C++. I consistently get the error in the main file.
#include <iostream>
#include "Ball.h"
Ball b;
int main()
{
// create the window
sf::RenderWindow window(sf::VideoMode(1200, 600), "My window");
// run the program as long as the window is open
while (window.isOpen())
{
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
window.close();
}
// clear the window with black color
window.clear(sf::Color::Black);
// draw everything here...
window.draw(b);
// end the current frame
window.display();
}
return 0;
}
This is the ball.h file:
#pragma once
#include <iostream>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
class Ball
{
public:
double x, y;
int Radius;
void Render(int Rad, sf::Color BallColour) {
sf::CircleShape shape(Rad);
// set the shape color to green
shape.setFillColor(BallColour);
}
};
I am unsure as to why the error occurs. Any help would be appreciated.
You had not call function of render, you just wrote window.draw(b), and programm dont know what do you mean. In Ball.h you should write:
#pragma once
#include <iostream>
#include <SFML/Window.hpp>
#include <SFML/Graphics.hpp>
class Ball
{
public:
double x, y;
int Radius;
void Render(int Rad, RenderWindow& window) {
sf::CircleShape shape(Rad);
// set the shape color to green
shape.setFillColor(sf::Color::Green);
shape.setPosition(600, 300);//SETTING POSITION OF THE BALL
window.draw(shape);//if you know what is reference on variable, you will understand what is it
}
};
And in your main.cpp you shhould call your function Render:
#include <iostream>
#include "Ball.h"
int main()
{
// create the window
sf::RenderWindow window(sf::VideoMode(1200, 600), "My window");
Ball b; //I advice you to create object of class in main function
// run the program as long as the window is open
while (window.isOpen())
{
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event))
{
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
window.close();
}
// clear the window with black color
window.clear(sf::Color::Black);
b.Render(10, window);// give the function reference on window
// end the current frame
window.display();
}
return 0;
}
sf::RenderWindow::draw requires an implementation of sf::Drawable. You can either pass sf::CircleShape (it's a sf::Drawable) directly or implement sf::Drawable and delegate the call.
class Ball : public sf::Drawable {
public:
double x, y;
int Radius;
void draw(sf::RenderTarget& target, sf::RenderStates states) const override {
sf::CircleShape shape(Radius);
shape.setFillColor(BallColour);
shape.draw(target, states);
}
};

How to draw an object onto sfml window when a function is called?

I have a character sprite moving across the screen and when I press 'a' I want the program to draw the sword sprite onto the screen and make the sword go away when I am not pressing 'a'. Currently I have an attack function that sets a showweapon boolean as true, and a if statement that is supposed to draw the weapon onto the screen but nothing happens. Is there a better way to do this?
main.cpp
#include <iostream>
#include <SFML/Graphics.hpp>
#include "Character.h"
#include "Projectile.h"
#include "Weapon.h"
using namespace std;
bool scroll = false;
Character player("/Users/danielrailic/Desktop/Xcode /NewGame/ExternalLibs/Player.png");
Weapon woodsword("/Users/danielrailic/Desktop/Xcode /NewGame/ExternalLibs/WoodSword.png");
bool showweapon;
int main() {
// insert code here...
int windowWidth = 5000;
int windowHeight = 5000;
sf::RenderWindow window(sf::VideoMode(windowWidth, windowHeight ), "Awesome Game" );
sf::Texture dungeon;
dungeon.loadFromFile("/Users/danielrailic/Desktop/Xcode /NewGame/ExternalLibs/DungeonBack.png");
sf::Sprite backround;
backround.setTexture(dungeon);
while (window.isOpen()){
// check all the window's events that were triggered since the last iteration of the loop
sf::Event event;
while (window.pollEvent(event)){
// "close requested" event: we close the window
if (event.type == sf::Event::Closed)
window.close();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)){
player.left();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)){
player.right();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)){
player.forward();
}
if (sf:: Keyboard::isKeyPressed(sf::Keyboard::Down)){
player.backward();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::LShift))
{
player.Highspeed();
}
else{
player.Lowspeed();
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)){
woodsword.attack();
}
window.clear(sf::Color(255, 255, 255));
window.draw(backround);
if(showweapon == true){
window.draw(woodsword.getSprite());
window.display();
cout << "Hello";
}
window.draw(player.getSprite());
window.display();
window.setFramerateLimit(70);
}
}
I am also not receiving the "hello" message
weapon.h
class Weapon : Character{
bool showweapon;
public:
sf::Texture texture;
//Constructor
Weapon(string wep)
: Character(wep){
texture.loadFromFile(wep);
showweapon = false;
}
sf::Sprite getSprite() {
sf::Sprite sprite;
sprite.setTexture(texture);
sprite.setTextureRect(sf::IntRect(0, 0, 100, 100));
sprite.setPosition(x_pos, y_pos);
return sprite;
}
//Methods
void attack();
};
void Weapon::attack(){
showweapon = true;
}
If you need to see anything else let me know. Thanks for any help!
I changed the if statement to : if (woodsword.showweapon == true) and I also made a sheath method in the weapon class that sets showweapon false so the sword goes away when I don't press 'a'. Thanks for everyones help.

SFML 2.0 - Drawing a starfield

I'm using sfml 2.0 to make a game. The background is going to be a starfield. Rather than use an image, I thought it might be neat to randomly generate a starfield each time the game starts up, so the background looks slightly different each time. Problem is, the way I'm currently doing it slows my game down A LOT. Does anyone know what is causing the speed hit? I've looked through the documentation to see what, but I haven't found anything...
Here's my code:
#include <SFML/Graphics.hpp>
#include "sfml helper/initialization_helpers.h"
#include "sfml helper/cursor_functions.h"
#include "sfml helper/global_event_handler.h"
#include "sfml helper/globals.h"
#include <cstdio>
int main(int argc, char* argv[])
{
try {
// some non-related preparations...
PrepareApplication(argv[0]);
float width = 640, height = 480;
sf::RenderWindow window(sf::VideoMode(width, height), "SFML Test", sf::Style::Close);
window.setFramerateLimit(60);
// Textures is a global object that has an internal std::map<string, sf::Texture>
Textures.add("ball.png", "ball");
sf::Sprite sprite;
sprite.setTexture(Textures.get("ball"));
// This is the snippet that generates the starfield
srand(time(NULL));
sf::Image starsImg;
starsImg.create(width, height, sf::Color::Black);
int numStars = rand() % 20 + 490;
for (int i = 0; i < numStars; i++) {
int x = rand() % (int)width;
int y = rand() % (int)height;
sf::Color color(255, 255, 255, rand() % 75 + 25);
starsImg.setPixel(x, y, color);
}
sf::Texture starsTexture;
starsTexture.loadFromImage(starsImg);
sf::Sprite stars;
stars.setTexture(starsTexture);
// main loop
while (window.isOpen()) {
if (Flags.isActive && Flags.inFocus) {
confineCursorToWindow(window);
} else {
freeCursor();
}
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::KeyPressed) {
if (event.key.code == sf::Keyboard::Escape) {
Flags.isActive = (!Flags.isActive);
}
}
if (event.type == sf::Event::MouseMoved) {
sprite.setPosition(event.mouseMove.x, event.mouseMove.y);
}
// handles default events like sf::Event::WindowClosed
handleDefaultEventsForWindow(event, window);
}
window.clear();
window.draw(stars); // here's where I draw the stars
window.draw(sprite);
window.display();
}
} catch (const char* error) {
printf("%s\n", error);
exit(1);
}
return 0;
}
EDIT
I tried loading an image of a starfield and tried drawing that, the game still runs slow!
Also, by slow, I mean the sprite called "sprite" lags when following the mouse. Is that actually a speed issue?