SFML class wont draw C++ - c++

this is my first post on SO, please forgive me if I don't do it right.
I am trying to draw some a simple hexagon grid using C++ SFML. The hex grid is created in it'sown class and called in main.
Hex class Header
class Terrain : public sf::Drawable, public sf::Transformable
{
public:
explicit Terrain(sf::Texture texture, int x, int y);
sf::Texture texture;
sf::CircleShape hexMethod(float x, float y, float Radius);
virtual void draw(sf::RenderTarget& target, sf::RenderStates states) const;
void cameraAngle();
void setTexture(sf::Texture);
void setX(int xint);
void setY(int yint);
void update(sf::Time deltaTime);
sf::Time T_currentTime;
private:
sf::Texture m_terrain;
int xcoord, ycoord;
sf::Vertex m_verticeList[6];
bool isOdd(int integer)
{
if (integer % 2 == 0)
return true;
else
return false;
}
//virtual ~Terrain()
//{
//}
};
Hex class cpp
Terrain::Terrain(sf::Texture texture, int x, int y) :
m_terrain(texture), xcoord(x), ycoord(y)
{
}
void Terrain::setTexture(sf::Texture newText)
{
m_terrain = newText;
}
void Terrain::setX(int xint)
{
xcoord = xint;
}
void Terrain::setY(int yint)
{
ycoord = yint;
}
sf::CircleShape Terrain::hexMethod(float x, float y, float Radius){
float Width = Radius * 2, Height = Width *sqrt(3) / 2;
sf::CircleShape shape(Radius, 6);
float origo = 200;
float yrsize;
float normalDistanceX = origo + Width * 3 / 4 * x;
float normalSeparationY = origo + Height*y;
float isEven = Height / 2;
shape.setTexture(&texture, false);
shape.setOutlineThickness(2);
shape.setOrigin(Radius, Radius);
shape.setRotation(30);
if (Terrain::isOdd(x))
yrsize = normalSeparationY;
else
yrsize = normalSeparationY + isEven;
shape.setPosition(normalDistanceX, yrsize);
m_verticeList[0] = shape.getPoint(0);
m_verticeList[1] = shape.getPoint(1);
m_verticeList[2] = shape.getPoint(2);
m_verticeList[3] = shape.getPoint(3);
m_verticeList[4] = shape.getPoint(4);
m_verticeList[5] = shape.getPoint(5);
return shape;
}
void Terrain::draw(sf::RenderTarget& target, sf::RenderStates states) const
{
for (size_t i = 0; i < 3; i++)
{
for (size_t j = 0; j < 3; j++)
{
states.transform *= getTransform();
states.texture = &m_terrain;
target.draw(m_verticeList, 4, sf::Points, states);
}
}
}
How I call it in main:
int main()
{
sf::RenderWindow window(sf::VideoMode(800, 800), "Puppet Masters!");
if (!tTexture.loadFromFile("Green.jpg"))
return EXIT_FAILURE;
Terrain newterrain(tTexture, 3,3);
newterrain.hexMethod(3, 3, 70);
while (window.isOpen())
{
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::P)
{
}
window.clear();
window.draw(newterrain);
window.display();
}
return 0;
}
I get no errors when running the code, however I also get no result, just a blank black screen. My intention is to have the hexes drawn from calling the class and defining it's variables. The Hexfunction I used in main at first to get a hex grid working, I don't think know how to translate that into a class properly.

Related

non-const lvalue reference to type 'Sprite' cannot bind to a temporary of type 'Sprite'

I am checking whether the player has collided with the bullet or not but it gives me an error saying non-const lvalue reference to type 'Sprite' cannot bind to a temporary of type 'Sprite'
here is my main.cpp
#include <SFML/Graphics.hpp>
#include "Player.hpp"
#include "Enemy.hpp"
#include "Game.cpp"
#include"Text.hpp"
#include <vector>
int main()
{
sf::RenderWindow window = sf::RenderWindow(sf::VideoMode(2000, 2000), "Space Outwaders", sf::Style::Close | sf::Style::Titlebar);
window.setFramerateLimit(240);
window.setMouseCursorVisible(false);
// clock
sf::Clock clock;
sf::Clock m_timeElapsed;
// ground
Sprite ground("assets/ground.png");
ground.setPosition(0, 1872);
// player
Player player("assets/player.png");
float gravity = 1.8;
player.setPosition(0, 1590);
//player Text
Text hearts("20","assets/hearts.ttf");
hearts.setSize(60);
hearts.setColor(sf::Color::Red);
// enemy
std::vector<std::pair<Enemy, float>> enemy;
Enemy s("assets/enemy.png");
enemy.push_back(std::pair<Enemy, float>(s, 100));
enemy.push_back(std::pair<Enemy, float>(s, 328));
enemy.push_back(std::pair<Enemy, float>(s, 556));
enemy.push_back(std::pair<Enemy, float>(s, 784));
enemy.push_back(std::pair<Enemy, float>(s, 986));
enemy.push_back(std::pair<Enemy, float>(s, 986 + 228));
int timeElapsedCount = 3;
// time
sf::Time c_time = clock.getElapsedTime();
float m_time = m_timeElapsed.getElapsedTime().asSeconds();
// game loop
sf::Event *ev = new sf::Event;
while (window.isOpen())
{
c_time = clock.getElapsedTime();
m_time = m_timeElapsed.getElapsedTime().asSeconds();
// game loop
ev = new sf::Event;
clock.restart().asSeconds();
if (!player.getCollision(ground))
{
player.move(0, gravity * c_time.asMilliseconds());
}
while (window.pollEvent(*ev))
{
if (ev->type == sf::Event::Closed)
{
window.close();
}
if (player.getSprite().getGlobalBounds().left > -1 && 1941 >= player.getSprite().getGlobalBounds().left)
{
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A) && player.getCollision(ground))
player.left(c_time.asMilliseconds()*2);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D) && player.getCollision(ground))
player.right(c_time.asMilliseconds()*2);
}
else if (player.getSprite().getGlobalBounds().left <= -1)
player.move(0.1, 0);
else
player.move(-0.1,0);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) && player.getCollision(ground))
player.move(0, 10);
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
player.move(0, -10);
}
window.clear(sf::Color(21, 21, 21));
ground.drawSprite(&window);
for (int i = 0; i < std::size(enemy); i++)
{
if (timeElapsedCount <= m_time)
{
timeElapsedCount = m_time+3;
std::cout << timeElapsedCount << std::endl;
}
else if(timeElapsedCount % 2 == 0)
enemy.at(i).second -= 1;
else
enemy.at(i).second += 1;
enemy.at(i).first.setColor(sf::Color(136, 136, 136));
enemy.at(i).first.setPosition(enemy.at(i).second, 0);
enemy.at(i).first.drawSprite(&window);
enemy.at(i).first.moveBullet(1.3*c_time.asMilliseconds(), &ground, &player);
enemy.at(i).first.drawBullet(&window);
if (player.getCollision( enemy.at(i).first.getBullet()))
{
/* code */
}
}
hearts.drawText(&window);
player.drawSprite(&window);
window.display();
delete ev;
}
return 0;
}
here is my sprite class:
#pragma once
#include <SFML/Graphics.hpp>
#include <iostream>
class Sprite
{
protected:
sf::Texture texture;
sf::Sprite sprite;
public:
Sprite(std::string fileName);
sf::Sprite getSprite();
void drawSprite(sf::RenderWindow *window);
void setPosition(int X, int Y);
void move(float X, float Y);
void setColor(sf::Color color);
};
Sprite ::Sprite (std::string fileName)
{
texture.loadFromFile(fileName);
sprite.setTexture(texture);
}
sf::Sprite Sprite ::getSprite()
{
return sprite;
}
void Sprite ::drawSprite(sf::RenderWindow *window)
{
window->draw(sprite);
}
void Sprite ::setPosition(int X, int Y)
{
sprite.setPosition(sf::Vector2f(X, Y));
}
void Sprite :: move(float X , float Y)
{
sprite.move(sf::Vector2f(X,Y));
}
void Sprite :: setColor(sf::Color color)
{
sprite.setColor(color);
}
and my enemy class :
#include "Game.hpp"
class Enemy : public Sprite
{
Sprite * bullet;
public:
void drawBullet(sf::RenderWindow * window);
Enemy(std::string fileName);
void moveBullet(float Y , Sprite * gameObject , Sprite * gameObject2);
void randomLeft(float amount);
auto getBullet();
};
Enemy :: Enemy(std::string fileName) : Sprite(fileName)
{
this->bullet = new Sprite("assets/bullet.png");
this->bullet->setPosition(this->sprite.getPosition().x+120,100);
}
void Enemy :: drawBullet(sf::RenderWindow * window)
{
window->draw(this->bullet->getSprite());
}
void Enemy :: moveBullet(float Y , Sprite * gameObject , Sprite * gameObject2)
{
if (bullet->getSprite().getGlobalBounds().intersects(gameObject->getSprite().getGlobalBounds()) || bullet->getSprite().getGlobalBounds().intersects(gameObject2->getSprite().getGlobalBounds()))
{
// delete bullet; this will give segmentation fault i have to fix this later
this->bullet = new Sprite("assets/bullet.png");
this->bullet->move(this->sprite.getPosition().x+56,100);
}
else
this->bullet->move(0,Y);
}
void Enemy :: randomLeft(float amount)
{
}
// srand((unsigned)time(NULL));
// for (int x = 0; x < 3; x++)
// {
// // Type casting the result to float
// cout << rand() / 10000000 << endl;
// cout << time(0) << std::endl;
// }
auto Enemy :: getBullet()
{
return *bullet;
}
the enemy class has a function that returns a Sprite class object.
and in the main.cpp I check where the player has collided but I keep getting this
error: non-const lvalue reference to type 'Sprite' cannot bind to a temporary of type 'Sprite'

How to create a layout of bricks for Breakout game using a data/text file in C++ SFML?

I am creating a classic breakout game in C++ using SFML library. So far I have a movable paddle and ball implemented.
Currently, my goal is to create a layout of bricks. So far I have it so that a single brick is displayed. However, I want to make it so that I can draw a layout of bricks in text file using a letter (For example using letter 'B'), read that text file's brick layout and draw that layout in game.
I am not sure how to do this so any help would be great!
Here is my code so far (Note that I did not include for Paddle and Ball as I thought it was not needed for this problem):
GameObject.h
#pragma once
#include <SFML/Graphics.hpp>
class GameObject
{
protected:
sf::Vector2f position;
float speed;
sf::RenderWindow& m_window;
public:
GameObject(float startX, float startY, sf::RenderWindow& window);
virtual ~GameObject() {};
virtual void Draw() = 0;
virtual void Update() = 0;
};
GameObject.cpp
#include "GameObject.h"
GameObject::GameObject(float startX, float startY, sf::RenderWindow& window)
: position{ startX, startY }
, speed{ 0.5f }
, m_window{ window }
{
}
Brick.h
#pragma once
#include "GameObject.h"
class Brick : public GameObject
{
private:
sf::RectangleShape brickShape;
static constexpr int shapeWidth = 50;
static constexpr int shapeHeight = 20;
int color;
int strength;
public:
Brick(float startX, float startY, sf::RenderWindow& window);
sf::FloatRect getPosition();
sf::RectangleShape getShape();
int getStrength();
void setStrength(int strengthValue);
void Draw() override;
void Update() override;
};
Brick.cpp
#include "Brick.h"
Brick::Brick(float startX, float startY, sf::RenderWindow& window)
: GameObject{ startX, startY, window }
{
brickShape.setSize(sf::Vector2f(shapeWidth, shapeHeight));
brickShape.setPosition(position);
color = (rand() % 2) + 1;
if (color == 1)
{
brickShape.setFillColor(sf::Color::Yellow);
strength = 1;
}
else
{
brickShape.setFillColor(sf::Color(255, 165, 0));
strength = 2;
}
}
sf::FloatRect Brick::getPosition()
{
return brickShape.getGlobalBounds();
}
sf::RectangleShape Brick::getShape()
{
return brickShape;
}
int Brick::getStrength()
{
return strength;
}
void Brick::setStrength(int strengthValue)
{
strength = strengthValue;
}
void Brick::Draw()
{
m_window.draw(brickShape);
}
void Brick::Update()
{
}
Game.h
#pragma once
#include <SFML/Graphics.hpp>
#include "Paddle.h"
#include "Ball.h"
#include "Brick.h"
#include <algorithm>
#include <fstream>
#include <iostream>
class Game
{
private:
sf::RenderWindow& m_window;
std::unique_ptr<Paddle> player;
std::unique_ptr<Ball> ball;
std::unique_ptr<Brick> brick;
std::vector<std::unique_ptr<Brick>>bricks;
int bricksCountX;
int bricksCountY;
public:
const unsigned int m_windowWidth;
const unsigned int m_windowHeight;
public:
Game(sf::RenderWindow& window, const unsigned int& windowWidth, const unsigned int& windowHeight);
float RandomFloat(float a, float b);
void ReadFile();
void HandleCollision();
void HandleInput();
void Draw();
void Update();
void Run();
};
Game.cpp
#include "Game.h"
Game::Game(sf::RenderWindow& window, const unsigned int& windowWidth, const unsigned int& windowHeight)
: m_window{ window }
, m_windowWidth{ windowWidth }
, m_windowHeight{ windowHeight }
{
player = std::make_unique<Paddle>(m_windowWidth/2, m_windowHeight - 70, m_window);
ball = std::make_unique<Ball>(m_windowWidth / 2, m_windowHeight / 2, m_window);
ReadFile();
for (int i = 0; i < bricksCountX; i++)
for (int j = 0; j < bricksCountY; j++)
bricks.emplace_back(std::make_unique<Brick>((i + 1.5) * ((long long)brick->getShape().getSize().x + 3) + 22,
(j + 5) * (brick->getShape().getSize().y + 3), m_window));
}
float Game::RandomFloat(float a, float b)
{
return ((b - a) * ((float)rand() / RAND_MAX)) + a;
}
void Game::ReadFile()
{
// Create a text string, which is used to output the text file
std::string bricksText;
int numOfLines = 0;
// Read from the text file
std::ifstream MyReadFile("Bricks Layout.txt");
// Use a while loop together with the getline() function to read the file line by line
while (std::getline(MyReadFile, bricksText))
{
++numOfLines;
// Output the text from the file
bricksCountX = bricksText.length();
std::cout << bricksCountX;
}
bricksCountY = numOfLines;
// Close the file
MyReadFile.close();
}
void Game::HandleCollision()
{
if (ball->getShape().getPosition().x - ball->getRadius() < 0.0f)
{
ball->reboundLeft();
}
else if (ball->getShape().getPosition().x + ball->getRadius() > m_windowWidth)
{
ball->reboundRight();
}
else if (ball->getShape().getPosition().y - ball->getRadius() < 0.0f)
{
ball->reboundTop();
}
else if (ball->getShape().getPosition().y + ball->getRadius() > m_windowHeight)
{
ball->ballAngle = ball->ballAngle * -1;
}
else if (ball->getPosition().intersects(player->getPosition()))
{
ball->reboundPaddle(*player);
}
for (unsigned int i = 0; i < bricks.size(); i++)
{
if (ball->getPosition().intersects(bricks[i]->getPosition()))
{
if (bricks[i]->getStrength() == 1)
{
ball->reboundBrick(*bricks[i]);
bricks.erase(std::remove(bricks.begin(), bricks.end(), bricks[i]), bricks.end());
}
else
{
ball->reboundBrick(*bricks[i]);
bricks[i]->setStrength(1);
}
}
}
}
void Game::HandleInput()
{
player->HandleInput();
}
void Game::Draw()
{
player->Draw();
ball->Draw();
for (unsigned int i = 0; i < bricks.size(); i++)
{
bricks[i]->Draw();
}
}
void Game::Update()
{
player->Update();
ball->Update();
brick->Update();
}
void Game::Run()
{
//Game Loop
while (m_window.isOpen())
{
sf::Event event;
while (m_window.pollEvent(event))
{
if (event.type == sf::Event::Closed || sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
m_window.close();
}
m_window.clear();
Draw();
HandleInput();
HandleCollision();
Update();
m_window.display();
}
}

2D Isometric(diamond shape) game engine - Reversed sprites

All my sprites are reversed when I try to draw my isometric map.
Here is the tileset.png mentionned in the following code :
Object.h/Object.cpp
I can use them to draw tiles, UI element, etc. ...
#pragma once
class Object {
public:
//FUNCTIONS
Object();
void addComponent(float value);
int getComponent(float index);
void editComponent(float index, float value);
void deleteComponent(float index);
private:
vector<int> components;
};
#include "Object.cpp"
-
#pragma once
//FUNCTIONS
Object::Object() {
//...
}
void Object::addComponent(float value) {
components.push_back(value);
}
int Object::getComponent(float index) {
return components[index];
}
void Object::editComponent(float index, float value) {
components[index] = value;
}
void Object::deleteComponent(float index) {
components.erase(components.begin() + index);
}
Note: I may have weird includes, I'm struggling with visual studio ha ha.
Scene.h/Scene.cpp
Handle data & graphics
#pragma once
class Scene {
public:
Scene(float w, float h, int mapx, int mapy, int tilesize, int mapwidth, int mapheight);
void run();
void addLayer();
void loadTileset(sf::String url);
void loadUiTileset(sf::String url);
//functions
//...
//getters
//...
//setters
//...
private:
sf::RenderWindow window;
float width;
float height;
int nb_layers;
int map_x;
int map_y;
int map_width;
int map_height;
int tile_size;
int selected_tile_index;
sf::RenderTexture texture;
sf::Sprite tile;
sf::Sprite map;
sf::Texture tileset;
vector<Object> tiles;
sf::Texture uiTileset;
//private functions
void updateMap();
//...
void processEvent();
void update(sf::Time deltaTime);
void render();
//...
};
#include "Scene.cpp"
-
#pragma once
//functions
Scene::Scene(float w, float h, int mapx, int mapy, int tilesize, int mapwidth, int mapheight) : window(sf::VideoMode(w, h), "Editor") {
width = w;
height = h;
map_x = mapx;
map_y = mapy;
map_width = mapwidth;
map_height = mapheight;
tile_size = tilesize;
selected_tile_index = 0;//default
nb_layers = 0;
}
void Scene::run() {
sf::Clock clock;
sf::Time timeSinceLastUpdate = sf::Time::Zero;
sf::Time TimePerFrame = sf::seconds(1.f / 60.f);
while (window.isOpen()) {
processEvent();
timeSinceLastUpdate += clock.restart();
while (timeSinceLastUpdate > TimePerFrame) {
timeSinceLastUpdate -= TimePerFrame;
processEvent();
update(TimePerFrame);
}
render();
}
}
void Scene::addLayer() {
nb_layers += 1;
int tile_x = map_x,
tile_y = map_y,
num_layer = nb_layers - 1,
layer_pos = (num_layer * tile_size) / 2,
tile_zOrder = -1;
tile_y -= layer_pos;
int x = map_x,
y = map_y;
for (int h = 0; h < map_height; h++) {
for (int w = 0; w < map_width; w++) {
tile_zOrder = (w * (h + 1)) + (num_layer * 10);
x = carthesianToIsometric(tile_x, tile_y)[0];
y = carthesianToIsometric(tile_x, tile_y)[1] - layer_pos;
cout << x << ", " << y << endl;
Object tile;
tile.addComponent(selected_tile_index);
tile.addComponent(x);
tile.addComponent(y);
tile.addComponent(tile_zOrder);
tile.addComponent(num_layer);
tiles.push_back(tile);
tile_x += tile_size;
}
tile_x = 0;
tile_y += tile_size;
}
updateMap();
}
void Scene::loadTileset(sf::String url) {
if (!tileset.loadFromFile(url))
{
cout << std::string(url) << "couldn't be loaded..." << endl;
}
}
void Scene::loadUiTileset(sf::String url) {
if (!uiTileset.loadFromFile(url))
{
cout << std::string(url) << "couldn't be loaded..." << endl;
}
}
//getters
//...
//setters
//...
//private functions
void Scene::updateMap() {
int tile_position_x = 0,
tile_position_y = 0;
int tile_x = 0,
tile_y = 0;
if (!texture.create(map_width * tile_size, (map_height * tile_size) / 2))
cout << "Texture couldn't be loaded... " << endl;
texture.clear(sf::Color(133, 118, 104, 255));
sf::Sprite image;
image.setTexture(tileset);
int tileset_width = image.getGlobalBounds().width,
tileset_height = image.getGlobalBounds().height;
tile.setTexture(tileset);
for (int tile_index = 0; tile_index < tiles.size(); tile_index++) {
tile_position_x = getTilePosition(tileset_width, tileset_height, tiles[tile_index].getComponent(0), tile_size)[0];
tile_position_y = getTilePosition(tileset_width, tileset_height, tiles[tile_index].getComponent(0), tile_size)[1];
tile.setTextureRect(sf::IntRect(tile_position_x, tile_position_y, tile_size, tile_size));
tile_x = tiles[tile_index].getComponent(1);
tile_y = tiles[tile_index].getComponent(2);
tile.setPosition(sf::Vector2f(tile_x, tile_y));
texture.draw(tile);
}
map.setTexture(texture.getTexture());
}
void Scene::processEvent() {
sf::Event event;
while (window.pollEvent(event)) {
switch (event.type) {
case sf::Event::Closed:
window.close();
break;
case sf::Event::KeyPressed:
if (event.key.code == sf::Keyboard::Escape)
window.close();
break;
}
}
}
void Scene::update(sf::Time deltaTime) {
//REMEMBER: distance = speed * time
//MOVEMENT, ANIMATIONS ETC. ..
}
void Scene::render() {
window.clear();
window.draw(map);
window.display();
}
main.cpp
#pragma once
//global functions + main headers + class headers =>
#include "globalfunctions.h"
int main() {
int map_width = 15,
map_height = 15,
tile_size = 64;
float scene_width = map_width * tile_size,
scene_height = (map_height * tile_size) / 2;
Scene engine(scene_width, scene_height, 0, 0, tile_size, map_width, map_height);
engine.loadTileset("tileset.png");
//engine.loadUiTileset("menu.png");
engine.addLayer();
//...
engine.run();
return EXIT_SUCCESS;
}
globalfunctions.h
Some utility functions.
getTilePosition(...) allow me to get x, y on a texture with a given tile index. Example : if I want to draw the tile n°0 of the tileset texture.
#pragma once
#include <SFML/System.hpp>
#include <SFML/Graphics.hpp>
#include <SFML/Window.hpp>
#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
vector<float> getTilePosition(float tileset_width, float tileset_height, float tile_index, float tile_size) {//In a tileset
float tileX = 0,
tileY = 0,
tilePerLine = 0;
tilePerLine = tileset_width / tile_size;
tileY = floor(tile_index / tilePerLine);
tileX = ((tile_index + 1) - (tileY * tilePerLine)) - 1;
tileX *= tile_size;
tileY *= tile_size;
vector<float> coords;
coords.push_back(tileX);
coords.push_back(tileY);
return coords;
}
vector<int> carthesianToIsometric(int x, int y) {
vector<int> coords;
float isoX = (x - y) / 2,
isoY = (x + y) / 4;
coords.push_back(isoX);
coords.push_back(isoY);
return coords;
}
#include "Object.h"
#include "Scene.h"
//...
And here, the WTF result I get :
Thanks for reading all that weird code !
Edit :
When I change
tile.setPosition(sf::Vector2f(tile_x, tile_y));
to
tile.setPosition(sf::Vector2f(0, 0));
in updateMap() from scene.cpp :
Unfortunatly, I cannot explain why. Maybe it will help you to understand the problem.
In case someone encounter the same problem :
As #Spectre suggested it was a problem of the sfml function draw().
http://en.sfml-dev.org/forums/index.php?topic=6903.0
You need to use display on the sf::renderTexture after your cleared it.

Creating a array of class objects (C++) [duplicate]

This question already has answers here:
How do I use arrays in C++?
(5 answers)
Closed 7 years ago.
I have been trying to make a simulator which involves ants randomly running around (for now...) I want to make a array of "Ant" to contain all my ant information and later functions. How would I do that?? (example with my code if possible)(I know java fairly well so if you could relate it to java that would be nice
//inclusions
#include <GLUT/glut.h>
#include <OpenGL/glu.h>
#include <OpenGL/gl.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
//declarations
//class declarations
void keyboard (unsigned char key, int x, int y);
void keyboardUp (unsigned char key, int x, int y);
void mouseLocation(int,int);
int onMouse;
int rightClick;
int a = 0;
int mx;
int my;
float red=1.0, blue=0, green=0;
class Ant {
int x;
int y;
int type;
Ant() { } // private default constructor
public:
Ant(int nx, int ny, int ntype)
{
x = nx;
y = ny;
type = ntype;
}
void SetX(int swagger)
{
x = swagger;
}
void SetY(int ny)
{
y = ny;
}
void SetType(int ntype)
{
type = ntype;
}
int GetX() { return x; }
int GetY() { return y; }
};
//mouse listener methods
void mouseLocation(int x,int y) {
mx = x;
my = y;
}
void mouseClicks(int button, int state, int x, int y) {
mx = x;
my = y;
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
onMouse = 1;
}
if(button == GLUT_LEFT_BUTTON && state == GLUT_UP) {
onMouse = 0;
}
if(button == GLUT_RIGHT_BUTTON && state == GLUT_UP) {
rightClick = 0;
}
if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) {
rightClick = 1;
}
}
//keylistner methods
void keyboard (unsigned char key, int x, int y)
{
if (key == 'a')
{
a = 1;
}
}
void keyboardUp (unsigned char key, int x, int y)
{
if(key == 'a')
{
a = 0;
}
}
//ant methods
int randommove(int position,int speed)
{
speed++;
int random = rand() %speed - speed/2 ;
position = position + random;
return position;
}
//drawing methods
Ant ant1(100,100,1);
Ant ant2(50,500,1);
//Here is the where I want to try the ant array something like
//Ant ants[x] and then I would fill in the values with the SetX, SetY... methods
void ant()
{
int a2 = randommove(ant1.GetX(),2);
ant1.SetX(a2);
glLineWidth(1);
glBegin(GL_LINES);
glColor4f(1, 0, 0, 1);
glVertex2i(ant1.GetX(),ant1.GetY());
glVertex2i(ant1.GetX()+5,ant1.GetY()+5);
glEnd();
}
void line1()
{
if(a == 1)
{
glLineWidth(2.5);
glBegin(GL_LINES);
glVertex2i(80,20);
glVertex2i(100,400);
glEnd();
}
}
void line2()
{
if(onMouse == 1)
{
glLineWidth(2.5);
glBegin(GL_LINES);
glVertex2i(200,20);
glVertex2i(100,400);
glEnd();
}
}
void rect1()
{
if(mx >= 50 && my >= 50)
{
int x = 100;
int y = 100;
int w = 100;
int h = 100;
unsigned int rgba = 0xff0000ff; // red, no alpha
glBegin(GL_QUADS);
glColor4f(((rgba>>24)&0xff)/255.0f,
((rgba>>16)&0xff)/255.0f,
((rgba>>8)&0xff)/255.0f,
(rgba&0xff)/255.0f);
glVertex3f(x,y,0);
glVertex3f(x+w,y,0);
glVertex3f(x+w,y+h,0);
glVertex3f(x,y+h,0);
glEnd();
glColor4f(1, 1, 1, 1);
}
}
void rect2()
{
if(rightClick == 1)
{
int w = 100;
int h = 100;
unsigned int rgba = 0xff0000ff; // red, no alpha
glBegin(GL_QUADS);
glColor4f(((rgba>>24)&0xff)/255.0f,
((rgba>>16)&0xff)/255.0f,
((rgba>>8)&0xff)/255.0f,
(rgba&0xff)/255.0f);
glVertex3f(mx,my,0);
glVertex3f(mx+w,my,0);
glVertex3f(mx+w,my+h,0);
glVertex3f(mx,my+h,0);
glEnd();
glColor4f(1, 1, 1, 1);
}
}
//render drawing methods
void renderScence(void){
glClear (GL_COLOR_BUFFER_BIT);
glColor3f(red, green, blue);
ant();
line1();
line2();
rect1();
rect2();
glFlush();
}
//graphics init method
void init(void)
{
glutInitDisplayMode(GLUT_SINGLE |GLUT_RGB);
glutInitWindowSize (500,500);
glutInitWindowPosition (100, 100);
glutCreateWindow ("Testing");
glClearColor (0, 0, 0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 500, 0, 500);
}
//main/graphics calls
int main(int argc,char** argv)
{
glutInit(&argc, argv);
init();
glutDisplayFunc(renderScence);
glutIdleFunc(renderScence);
glutMouseFunc(mouseClicks);
glutPassiveMotionFunc(mouseLocation);
glutKeyboardUpFunc (keyboardUp);
glutKeyboardFunc (keyboard);
glutMainLoop();
return 0;
}
You could create the array of Ant objects inside main, and it's the same way you'd create any other array except it's of type Ant:
Ant ants[25]; // 25 Ant objects
/* to set them all the same, as an example */
for(i=0; i<25; i++)
{
ants[i].SetX(1); // x = 1
ants[i].SetY(2); // y = 2
ants[i].SetType(3); // type = 3
}

C++ declaring classes/objects for a noobie

I have recently decided to try to learn c++. My major road block so far is object/class declaration I am reasonably experienced in java but the way c++ works confuses me. Can someone please show me a example of using a object (like the one below if possible) inside one file or multiple files? here is my current code (object is not implemented).
//inclusions
#include <GLUT/glut.h>
#include <OpenGL/glu.h>
#include <OpenGL/gl.h>
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
//declarations
void keyboard (unsigned char key, int x, int y);
void keyboardUp (unsigned char key, int x, int y);
void mouseLocation(int,int);
int onMouse;
int rightClick;
int a = 0;
int mx;
int my;
float red=1.0, blue=0, green=0;
class Ant
{
private:
int x;
int y;
int speed;
Ant() { } // private default constructor
public:
Ant(int nx, int ny, int nspeed)
{
SetX(nx);
SetY(ny);
SetSpeed(nspeed);
}
void SetX(int nx)
{
x = nx;
}
void SetY(int ny)
{
y = ny;
}
void SetSpeed(int nspeed)
{
speed = nspeed;
}
int GetX() { return x; }
int GetY() { return y; }
int GetSpeed() { return speed; }
};
//mouse listener methods
void mouseLocation(int x,int y) {
mx = x;
my = y;
}
void mouseClicks(int button, int state, int x, int y) {
mx = x;
my = y;
if(button == GLUT_LEFT_BUTTON && state == GLUT_DOWN) {
onMouse = 1;
}
if(button == GLUT_LEFT_BUTTON && state == GLUT_UP) {
onMouse = 0;
}
if(button == GLUT_RIGHT_BUTTON && state == GLUT_UP) {
rightClick = 0;
}
if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN) {
rightClick = 1;
}
}
//keylistner methods
void keyboard (unsigned char key, int x, int y)
{
if (key == 'a')
{
a = 1;
}
}
void keyboardUp (unsigned char key, int x, int y)
{
if(key == 'a')
{
a = 0;
}
}
//drawing methods
void line1()
{
if(a == 1)
{
glLineWidth(2.5);
glBegin(GL_LINES);
glVertex2i(20,20);
glVertex2i(100,400);
glEnd();
}
}
void line2()
{
if(onMouse == 1)
{
glLineWidth(2.5);
glBegin(GL_LINES);
glVertex2i(200,20);
glVertex2i(100,400);
glEnd();
}
}
void rect1()
{
if(mx >= 50 && my >= 50)
{
int x = 100;
int y = 100;
int w = 100;
int h = 100;
unsigned int rgba = 0xff0000ff; // red, no alpha
glBegin(GL_QUADS);
glColor4f(((rgba>>24)&0xff)/255.0f,
((rgba>>16)&0xff)/255.0f,
((rgba>>8)&0xff)/255.0f,
(rgba&0xff)/255.0f);
glVertex3f(x,y,0);
glVertex3f(x+w,y,0);
glVertex3f(x+w,y+h,0);
glVertex3f(x,y+h,0);
glEnd();
glColor4f(1, 1, 1, 1);
}
}
void rect2()
{
if(rightClick == 1)
{
int x = 100;
int y = 100;
int w = 100;
int h = 100;
unsigned int rgba = 0xff0000ff; // red, no alpha
glBegin(GL_QUADS);
glColor4f(((rgba>>24)&0xff)/255.0f,
((rgba>>16)&0xff)/255.0f,
((rgba>>8)&0xff)/255.0f,
(rgba&0xff)/255.0f);
glVertex3f(mx,my,0);
glVertex3f(mx+w,my,0);
glVertex3f(mx+w,my+h,0);
glVertex3f(mx,my+h,0);
glEnd();
glColor4f(1, 1, 1, 1);
}
}
//render drawing methods
void renderScence(void){
glClear (GL_COLOR_BUFFER_BIT);
glColor3f(red, green, blue);
line1();
line2();
rect1();
rect2();
glFlush();
}
//graphics init method
void init(void)
{
glutInitDisplayMode(GLUT_SINGLE |GLUT_RGB);
glutInitWindowSize (500,500);
glutInitWindowPosition (100, 100);
glutCreateWindow ("Testing");
glClearColor (0, 0, 0, 1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0, 500, 0, 500);
}
//main/graphics calls
int main(int argc,char** argv)
{
glutInit(&argc, argv);
init();
glutDisplayFunc(renderScence);
glutIdleFunc(renderScence);
glutMouseFunc(mouseClicks);
glutPassiveMotionFunc(mouseLocation);
glutKeyboardUpFunc (keyboardUp);
glutKeyboardFunc (keyboard);
glutMainLoop();
return 0;
}
Your class definition is correct (although a bit Javaish). You can create and use an object of type Ant like this:
Ant a(3, 7, 82);
a.SetSpeed(42);
int speed = a.GetSpeed();