Draw a 9 point circle in openGL? - c++

I'm trying to draw a 9 point circle for my openGL class project, the problem? My teacher has not taught us how to do hardly anything with circles. He gave us code on how to 'draw' a triangle and told us what the formula to find vertex and center points for normal circles. But never once even touched on how to use them for coding, especially with his way he wants us to do it. He told us to use
class GLintPoint {
public:
GLint x, y;
};
and we could name them A, B, C then find the vertex say a = B - A. I assume this would be a.x = B.x - A.x and same for why, but I don't know for sure. He had to leave for a medical thing(I assume surgery) so I can't ask him and he still has it due at the end of the week.
He gave us this code before he left.
#include <stdlib.h>
#include <math.h>
#include <GL/glut.h>
#include "canvas.h"
const int screenWidth = 640;
const int screenHeight = 480;
Canvas cvs(screenWidth, screenHeight, "Relative Drawing Example", 1);
class GLintPoint {
public:
GLint x, y;
};
#define NUM 3
static GLintPoint List[NUM];
// myInit
void myInit(void)
{
glClearColor(1.0, 1.0, 1.0, 0.0);
glColor3f(0.0f, 0.0f, 0.0f);
glPointSize(1.0);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
gluOrtho2D(0.0, (GLdouble )screenWidth, 0.0, (GLdouble)screenHeight);
}
// myDisplay
void myDisplay(void)
{
glClear(GL_COLOR_BUFFER_BIT);
glFlush();
}
void mykey(unsigned char key, int x, int y)
{
if (key == 'Q' || key == 'q') exit(0);
}
// draw arc
void draw_arc(GLdouble cx, GLdouble cy, GLdouble r, GLdouble startAngle,
GLdouble sweepAngle)
{
glBegin(GL_LINE_STRIP);
for (GLdouble t = startAngle; t < startAngle+sweepAngle; t += 0.001)
{
GLdouble x = cx + r*cos(DEG2RAD*t);
GLdouble y = cy + r*sin(DEG2RAD*t);
glVertex2d(x, y);
}
glEnd();
}
// myMouse
void myMouse(int button, int state, int x, int y)
{
static int last = -1;
if (button == GLUT_LEFT_BUTTON && state == GLUT_DOWN && last < (NUM -1))
{
List[++last].x = x;
List[ last].y = screenHeight - y;
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_LINE_STRIP);
for (int i = 0; i <= last; i++) {
if(last <=0){
cvs.moveTo(List[i].x, List[i].y);
}
else
cvs.lineTo(List[i].x, List[i].y);
}
int i = 0;
cvs.lineTo(List[i].x, List[i].y);
glEnd();
glFlush();
}
else if(button == GLUT_RIGHT_BUTTON && state == GLUT_DOWN)
last = -1;
GLintPoint a.x =
}
// main
int main(int argc, char ** argv)
{
//glutInit(&argc, argv);
//glutInitDisplayMode(GLUT_SINGLE| GLUT_RGB);
//glutInitWindowSize(screenWidth, screenHeight);
//glutInitWindowPosition(100, 150);
//glutCreateWindow("case study 4.2");
glutDisplayFunc(myDisplay);
glutMouseFunc(myMouse);
glutKeyboardFunc(mykey);
myInit();
glutMainLoop();
return 0;
}
and
#include <math.h>
// define some ascii key names
#define GLUT_KEY_ESC 27
// Keeps track of a single point ( turtle position )
class Point2d {
public:
Point2d() { x = y = 0.0f; }
Point2d( float xx, float yy ) { x = xx; y = yy; }
void set( float xx, float yy ) { x = xx; y = yy; }
void setX( float xx ) { x = xx; }
void setY( float yy ) { y = yy; }
float getX() { return x; }
float getY() { return y; }
void draw( void ) { glBegin( GL_POINTS );
glVertex2f( (GLfloat)x, (GLfloat)y );
glEnd();
}
private:
float x, y;
};
//Data type for an array of points
class Point2dArray {
static const int MAX_NUM = 100;
public:
int num;
Point2d pt[MAX_NUM];
};
class IntRect {
public:
IntRect() { l = 0; r = 100; b = 0; t = 100; }
IntRect( int left, int right, int bottom, int top )
{ l = left; r = right; b = bottom; t = top; }
void set( int left, int right, int bottom, int top )
{ l = left; r = right; b = bottom; t = top; }
void draw( void ) { glRecti( l, b, r, t ); }
int getL() { return l; }
int getR() { return r; }
int getT() { return t; }
int getB() { return b; }
private:
int l, r, b, t;
};
class RealRect {
public:
RealRect() { l = 0; r = 100; b = 0; t = 100; }
RealRect( float left, float right, float bottom, float top )
{ l = left; r = right; b = bottom; t = top; }
void set( float left, float right, float bottom, float top )
{ l = left; r = right; b = bottom; t = top; }
void draw( void ) { glRectf( l, b, r, t ); }
float ratio( void ) { return (r - l)/(t - b); }
float getL() { return l; }
float getR() { return r; }
float getT() { return t; }
float getB() { return b; }
private:
float l, r, b, t;
};
class Canvas {
public:
Canvas( int width, int height, char* windowTitle, int buffer );
void setWindow( float l, float r, float b, float t );
void setViewport( int w, int h );
void autoSetWindow(void);
float getWindowAspectRatio( void );
void lineTo( float x, float y );
void lineTo( Point2d p );
void moveTo( float x, float y );
void moveTo( Point2d p );
void turnTo( float angle );
void turn( float angle );
void forward( float dist, int visible );
int getWinId(void);
void initCT(void);
void scale2D(double, double);
void translate2D(double, double);
void rotate2D(double);
private:
Point2d CP;
float CD;
IntRect viewport;
RealRect window;
int winId;
float delx, dely;
char code1, code2;
char formCode(Point2d p);
void chopLine(Point2d &p, char c);
int clipSegment(Point2d &p1, Point2d &p2);
};
Canvas::Canvas( int width, int height, char* windowTitle, int buffer = 1 ) {
char* argv[1];
char dummyString[1];
argv[0] = dummyString;
int argc = 1;
glutInit( &argc, argv );
glutInitDisplayMode( ((buffer == 1) ? GLUT_SINGLE : GLUT_DOUBLE) | GLUT_RGB );
glutInitWindowSize( width, height );
glutInitWindowPosition( (1024 - width) / 2, (768 - height) / 2 );
winId = glutCreateWindow( windowTitle );
setWindow( 1000.0f, -1000.0f, 1000.0f, -1000.0f );
CP.set( 0.0f, 0.0f );
CD = 0.0f;
}
int Canvas::getWinId(void)
{
return winId;
}
float Canvas::getWindowAspectRatio(void)
{
return (window.getR() - window.getL())/(window.getT() - window.getB());
}
void Canvas::setWindow( float l, float r, float b, float t ) {
window.set( l, r, b, t );
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( (GLdouble) l, (GLdouble) r, (GLdouble) b, (GLdouble) t );
}
void Canvas::autoSetWindow(void) {
float l = window.getL();
float r = window.getR();
float b = window.getB();
float t = window.getT();
glMatrixMode( GL_PROJECTION );
glLoadIdentity();
gluOrtho2D( (GLdouble) l, (GLdouble) r, (GLdouble) b, (GLdouble) t);
}
void Canvas::setViewport( GLsizei width, GLsizei height) {
float aspectRatio = getWindowAspectRatio();
GLint l, b;
GLsizei w, h;
if ((float) width / (float) height >= aspectRatio) {
l = (GLint) ((width - height * aspectRatio)/2.0);
b = 0;
w = (GLsizei) (height * aspectRatio);
h = height;
}
else {
l = 0;
b = (int) ((height - width / aspectRatio)/2.0);
w = width;
h = (GLsizei) (width / aspectRatio);
}
glViewport( l, b, w, h );
}
void Canvas::lineTo( float x, float y ) {
glBegin( GL_LINES );
glVertex2f( (GLfloat) CP.getX(), (GLfloat) CP.getY() );
glVertex2f( (GLfloat) x, (GLfloat) y );
glEnd();
CP.set( x, y );
glFlush();
}
void Canvas::lineTo( Point2d p ) {
glBegin( GL_LINES );
glVertex2f( (GLfloat) CP.getX(), (GLfloat) CP.getY() );
glVertex2f( (GLfloat) p.getX(), (GLfloat) p.getY() );
glEnd();
CP.set( p.getX(), p.getY() );
glFlush();
}
void Canvas::moveTo( float x, float y ) {
CP.set( x, y );
}
void Canvas::moveTo( Point2d p ) {
CP.set( p.getX(), p.getY() );
}
void Canvas::turn(float angle) {
CD += angle;
}
void Canvas::turnTo(float angle) {
CD = angle;
}
void Canvas::forward( float dist, int visible ) {
const float RadPerDeg=0.017453393;
float x = CP.getX()+dist*cos(RadPerDeg*CD);
float y = CP.getY()+dist*sin(RadPerDeg*CD);
float l = window.getL();
float r = window.getR();
float b = window.getB();
float t = window.getT();
l = (x < l)?x:l;
r = (x > r)?x:r;
b = (y < b)?y:b;
t = (y > t)?y:t;
window.set(l, r, b, t);
if (visible)
lineTo(x, y);
else
moveTo(x, y);
}
And these formulas. Written just as the piece of paper he gave me reads
a = B -A
b = C - B
c - A - C
c = A = 1/2((a + ((b(dot product) c)/(matrix of a (dotproduct)c)) * (matrix of a))
r = (magnitude of a)/2 squareroot(((b(dot product) c)/(matrix of a (dotproduct)c))^2 + 1)
I hate to ask, but I know when I'm in over my head, can anyone make heads or tails of what hes asking me to do? Or can anyone lead me in the right direction for how to make a 9 point circle? Its worth 10% of my final grade, so I'm not asking for the code to just copy/paste just "wtf do I do?" is all I'm asking.

You can't really draw curves in OpenGL, just polygons. So if someone asked me to draw a nine point circle in OpenGL, I would assume they meant a polygon with 9 sides, where each each point is evenly spaced along the perimeter of a circle.

Related

How to check whether mouse clicked over a polygon in OpenGL?

I'm trying to make a color picker tool in OpenGL. It works you can use the code below. However there is one glaring issue, if you test the program you will find that if you click the black background, the color selected will become black. So my question is how do I change the code such that it recognizes which polygon I clicked or recognizes that I clicked on something or a polygon.
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#include <iostream>
#include <cmath>
#include <iterator>
//static void mouseButtonCallback(GLFWwindow* window, int button, int action, int mod);
static void mouse_cursor_callback(GLFWwindow* window, double xpos, double ypos);
float randfloat(){
float r = ((float)(rand() % 10))/10;
return r;
}
class RGB{
public:
float r;
float g;
float b;
void setColor(float _r, float _g, float _b){
r = _r;
g = _g;
b = _b;
}
};
RGB selected_col;
RGB mixColor(RGB color1, RGB color2){
float r = 0;
float g = 0;
float b = 0;
r = sqrt((pow(color1.r,2)+pow(color2.r,2))/2);
g = sqrt((pow(color1.g,2)+pow(color2.g,2))/2);
b = sqrt((pow(color1.b,2)+pow(color2.b,2))/2);
RGB a;
a.setColor(r,g,b);
return a;
}
int main() {
int side_count;
std::cout<<"Type the no. of sides: "<<std::endl;
std::cin>>side_count;
if(side_count < 3){
return 1;
}
srand((unsigned)time(0));
float rs[side_count];
float gs[side_count];
float bs[side_count];
RGB colors[side_count];
for (int i=0;i<side_count;i++)
{
rs[i] = randfloat();
gs[i] = randfloat();
bs[i] = randfloat();
colors[i].setColor(rs[i],gs[i],bs[i]);
}
GLFWwindow* window;
if (!glfwInit())
return 1;
window = glfwCreateWindow(400, 400, "Window", NULL, NULL);
//glfwSetMouseButtonCallback(window, mouseButtonCallback);
glfwSetCursorPosCallback(window, mouse_cursor_callback);
if (!window) {
glfwTerminate();
return 1;
}
glfwMakeContextCurrent(window);
if(glewInit()!=GLEW_OK)
std::cout<<"Error"<<std::endl;
RGB mcol = colors[1];
for(int i=0;i<side_count-1;i++)
{
mcol = mixColor(mcol, colors[i+1]);
}
while(!glfwWindowShouldClose(window)) {
glClear(GL_COLOR_BUFFER_BIT);
glBegin(GL_POLYGON);
glColor3f(mcol.r,mcol.g,mcol.b);glVertex2f(0,0);
//glColor3f(1.0f,0.0f,0.0f);glVertex3f(-0.5f,0.0f,0.0f);
for(int i=0; i<=side_count;i++)
{
float r = rs[i%side_count];
float g = gs[i%side_count];
float b = bs[i%side_count];
float x = 0.5f * sin(2.0*M_PI*i/side_count);
float y = 0.5f * cos(2.0*M_PI*i/side_count);
glColor3f(r,g,b);glVertex2f(x,y);
}
glEnd();
glBegin(GL_QUADS);
glColor3f(selected_col.r, selected_col.g, selected_col.b);glVertex2f(-1.0f,0.5f);
glColor3f(selected_col.r, selected_col.g, selected_col.b);glVertex2f(-.5f,0.5f);
glColor3f(selected_col.r, selected_col.g, selected_col.b);glVertex2f(-.5f,1.5f);
glColor3f(selected_col.r, selected_col.g, selected_col.b);glVertex2f(-1.0f,1.5f);
glEnd();
glfwSwapBuffers(window);
glfwPollEvents();
}
glfwTerminate();
return 0;
}
/*static void mouseButtonCallback(GLFWwindow* window, int button, int action, int mods){
if(button == GLFW_MOUSE_BUTTON_LEFT && action == GLFW_PRESS){
double xPos, yPos;
glfwGetCursorPos(window, &xPos, &yPos);
//std::cout<<"X: "<<xPos<<" Y: "<<yPos<<std::endl;
double x=xPos;
int height,width;
glfwGetWindowSize(window, &width, &height);
double y = height - yPos;
unsigned char pixel[4];
glReadPixels(x, y, 1, 1, GL_RGB,GL_UNSIGNED_BYTE, &pixel);
selected_col.setColor((float)pixel[0]/255,(float)pixel[1]/255,(float)pixel[2]/255);
//std::cout<<"R: "<<selected_col.r<<" G: "<<selected_col.g<<" B: "<<selected_col.b<<std::endl;
}
}*/
void mouse_cursor_callback( GLFWwindow * window, double xpos, double ypos)
{
if (glfwGetMouseButton(window, GLFW_MOUSE_BUTTON_LEFT) == GLFW_RELEASE)
{
return;
}
double xPos, yPos;
glfwGetCursorPos(window, &xPos, &yPos);
//std::cout<<"X: "<<xPos<<" Y: "<<yPos<<std::endl;
double x=xPos;
int height,width;
glfwGetWindowSize(window, &width, &height);
double y = height - yPos;
unsigned char pixel[4];
glReadPixels(x, y, 1, 1, GL_RGB,GL_UNSIGNED_BYTE, &pixel);
selected_col.setColor((float)pixel[0]/255,(float)pixel[1]/255,(float)pixel[2]/255);
//std::cout<<"R: "<<selected_col.r<<" G: "<<selected_col.g<<" B: "<<selected_col.b<<std::endl;
}

Why doesn't OpenGL draw object from std::vector?

Why isn't it drawing object from vector? Where's my mistake?
It shows m_x,m_y position like this object would exist but this object isn't on my screen.
main.cpp:
#include <iostream>
#include <vector>
#define NDEBUG
#include "Figura.h"
#include "Balon.h"
#include <GL/freeglut.h>
using namespace std;
vector<CBalon> wektor_kol;
/* GLUT callback Handlers */
void resize(int width, int height)
{
const float ar = (float)width / (float)height;
glViewport(0, 0, width, height);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glFrustum(-ar, ar, -1.0, 1.0, 2.0, 100.0);
gluLookAt(0, 0, 5, 0, 0, 0, 0, 1, 0);
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
}
void idle()
{
glutPostRedisplay();
}
void DrawRectangle(double width, double height)
{
glPushMatrix();
// TODO
// test functions below (glTranslated, glRotated, glColor3d) - what happen when you change their arguments?
// does their order change the result?
glTranslated(0.0, 0.0, 0.0);
glRotated(0, 1.0, 0.0, 0.0);
glRotated(0, 0.0, 1.0, 0.0);
glRotated(0, 0.0, 0.0, 1.0);
glColor3d(1.0, 0.0, 0.0);
glBegin(GL_POLYGON);
{
glVertex3d(-width / 2, height / 2, 0);
glVertex3d(width / 2, height / 2, 0);
glVertex3d(width / 2, -height / 2, 0);
glVertex3d(-width / 2, -height / 2, 0);
}
glEnd();
glPopMatrix();
}
void display()
{
// clear the scene
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
glPushMatrix();
for (auto itr = wektor_kol.begin(); itr != wektor_kol.end(); itr++)
{
(*itr).Rysuj();
}
glPopMatrix();
glutSwapBuffers();
}
void InitGLUTScene(char* window_name)
{
glutInitWindowSize(800, 600);
glutInitWindowPosition(40, 40);
glutInitDisplayMode(GLUT_RGB | GLUT_DOUBLE | GLUT_DEPTH | GLUT_MULTISAMPLE);
glutCreateWindow(window_name);
// set white as the clear colour
glClearColor(1, 1, 1, 1);
glEnable(GL_DEPTH_TEST);
glDepthFunc(GL_LESS);
glEnable(GL_LIGHT0);
glEnable(GL_NORMALIZE);
glEnable(GL_COLOR_MATERIAL);
}
void SetCallbackFunctions()
{
glutReshapeFunc(resize);
glutDisplayFunc(display);
glutIdleFunc(idle);
}
void SetObjectsPositions()
{
CBalon balonik(0.6, 0.1, 0.5, 0.5);
balonik.positionSetter(0, 0);
wektor_kol.push_back(balonik);
}
int main(int argc, char *argv[])
{
// it's still possible to use console to print messages
printf("Hello openGL world!");
// the same can be done with cout / cin
glutInit(&argc, argv);
InitGLUTScene("freeglut template");
SetCallbackFunctions();
SetObjectsPositions();
// start GLUT event loop. It ends when user close the window.
glutMainLoop();
return 0;
}
Balon.cpp
#include "Balon.h"
#include "Figura.h"
#define NDEBUG
#define M_PI 3.14
#include <math.h>
#include <GL/freeglut.h>
CBalon::CBalon()
{
}
CBalon::CBalon(double radius, double red, double green, double blue)
{
m_r = red;
m_g = green;
m_b = blue;
m_radius = radius;
}
void CBalon::Rysuj()
{
glPushMatrix();
{
glTranslated(m_x, m_y, 0.0);
glRotated(m_z, 0.0, 0.0, 1.0);
glColor3d(m_r, m_g, m_b);
glBegin(GL_TRIANGLE_FAN);
{
for (int i = 0; i <= 360; i++)
{
// 180 - pi
// i - degInRad
float degInRad = i*M_PI / 180;
glVertex2f(cos(degInRad)*m_radius, sin(degInRad)*m_radius);
}
}
glEnd();
}
glPopMatrix();
}
double CBalon::redGetter()
{
return m_r;
}
CBalon::~CBalon()
{
}
Balon.h
#pragma once
#include "Figura.h"
class CBalon : public Figura
{
private:
double m_radius;
public:
CBalon();
CBalon(double radius, double red, double green, double blue);
double redGetter();
void Rysuj();
~CBalon();
};
Figura.cpp
#include "Figura.h"
Figura::Figura()
{
}
Figura::Figura(double _x, double _y, double _z, double _r, double _g, double _b, bool _u, double _rotation) : m_x(_x), m_y(_y), m_z(_z), m_r(_r), m_g(_g), m_b(_b), m_ukryj(_u), m_rotation(_rotation)
{
}
Figura::Figura(double red, double green, double blue)
: m_r(red), m_g(green), m_b(blue)
{
m_x = 0.0;
m_y = 0.0;
m_z = 0.0;
m_ukryj = true;
}
void Figura::Przesun(double dx, double dy)
{
m_x += dx;
m_y += dy;
}
bool Figura::GetterUkryj()
{
return m_ukryj;
}
void Figura::ZmienKolor(double _r, double _g, double _b)
{
m_r = _r;
m_g = _g;
m_b = _b;
}
double Figura::xGetter()
{
return m_x;
}
double Figura::yGetter()
{
return m_y;
}
void Figura::positionSetter(double x, double y)
{
m_x = x;
m_y = y;
}
Figura::~Figura()
{
}
Figura.h
#pragma once
class Figura
{
protected:
double m_r, m_g, m_b;
bool m_ukryj;
double m_x, m_y, m_z;
double m_alpha, m_beta, m_gamma;
double m_rotation;
public:
Figura();
Figura(double _x, double _y, double _z, double _r, double _g, double _b, bool _u, double _rotation);
Figura(double red, double green, double blue);
~Figura();
virtual void Rysuj() = 0;
void Ukryj();
void Pokaz();
void Przesun(double dx, double dy);
void Obroc(double dalpha, double dbeta, double dgamma);
void ZmienKolor(double _r, double _g, double _b);
double xGetter();
double yGetter();
void positionSetter(double x, double y);
bool GetterUkryj();
};
The mistake was:
CBalon::CBalon(double radius, double red, double green, double blue): Figura(),m_radius(radius)
{
m_r = red;
m_g = green;
m_b = blue;
}
Changing to:
CBalon::CBalon(double radius, double red, double green, double blue): Figura(red, green, blue),m_radius(radius)
{
}
solved my problem.

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();

Cannot place Collision Detection debug rectangle over game sprites

I am following along Let's Make An RPG (C++/SDL2) - Tutorials on Youtube and am stuck on Let's Make an RPG (C++/SDL2) - Part 35 Continuation on Collision (https://www.youtube.com/watch?v=DLu6g2S3Ta0&list=PLHM_A02NtaaVey-4Ezh7p6bbOsv-DKA-0).
I am trying to place a transparent rectangle over all sprites to debug collision detection. I am not getting any errors so there is no one piece of code I can show you.
Can someone please shed some light on where I went wrong. I'm very new to C++ but I'm not giving up. Thank you for your time. I'm genuinely grateful.
This is the code for both the header and cpp file of the Collision Rectangle
#include "CollisionRectangle.h"
CollisionRectangle::CollisionRectangle()
{
OffsetX = 0;
OffsetY = 0;
SetRectangle(0,0,0,0);
}
CollisionRectangle::CollisionRectangle(int x, int y, int w, int h)
{
OffsetX = x;
OffsetY = y;
SetRectangle(0,0,w,h);
}
CollisionRectangle::~CollisionRectangle()
{
//dtor
}
void CollisionRectangle::SetRectangle(int x, int y, int w, int h)
{
CollisionRect.x = x + OffsetY;
CollisionRect.y = y + OffsetY;
CollisionRect.w = w;
CollisionRect.h = h;
}
//header
#pragma once
#include "stdafx.h"
class CollisionRectangle
{
public:
CollisionRectangle();
CollisionRectangle(int x, int y, int w, int h);
~CollisionRectangle(void);
void SetRectangle(int x, int y, int w, int h);
SDL_Rect GetRectangle(){ return CollisionRect; }
void setX(int x){ CollisionRect.x = x + OffsetX; }
void setY(int y){ CollisionRect.y = y + OffsetY; }
private:
int OffsetX;
int OffsetY;
SDL_Rect CollisionRect;
};
This is the code for the both the header and the cpp file of Sprites
#include "Sprite.h"
Sprite::Sprite(SDL_Renderer* passed_renderer, std::string FilePath, int x, int y, int w, int h, float *passed_CameraX, float *passed_CameraY, CollisionRectangle passed_CollisionRect)
{
CollisionRect = passed_CollisionRect;
renderer = passed_renderer;
CollisionSDL_Rect = CollisionRect.GetRectangle();
image = NULL;
image = IMG_LoadTexture(renderer, FilePath.c_str());
if (image == NULL)
{
std::cout << "Couldn't load " << FilePath.c_str() << std::endl;
}
CollisionImage = NULL;
CollisionImage = IMG_LoadTexture(renderer, "Data/DebugImages/DebugBox.png");
if (CollisionImage == NULL)
{
std::cout << "Couldn't load " << "CollisionImage" << std::endl;
}
rect.x = x;
rect.y = y;
rect.w = w;
rect.h = h;
SDL_QueryTexture(image,NULL,NULL, &img_width, &img_height);
crop.x = 0;
crop.y = 0;
crop.w = img_width;
crop.h = img_height;
X_pos = x;
Y_pos = y;
Origin_X = 0;
Origin_Y = 0;
CurrentFrame = 0;
Amount_Frame_X = 0;
Amount_Frame_Y = 0;
CameraX = passed_CameraX;
CameraY = passed_CameraY;
Camera.x = rect.x + *CameraX;
Camera.y = rect.y + *CameraY;
Camera.w = rect.w;
Camera.h = rect.h;
}
void Sprite::DrawSteady()
{
SDL_RenderCopy(renderer,image, &crop, &rect);
}
void Sprite::Draw()
{
Camera.x = rect.x + *CameraX;
Camera.y = rect.y + *CameraY;
CollisionRect.setX(rect.x + *CameraX);
CollisionRect.setY(rect.y + *CameraY);
SDL_RenderCopy(renderer,image, &crop, &Camera);
SDL_RenderCopy(renderer,CollisionImage, NULL, &CollisionSDL_Rect);
}
void Sprite::SetUpAnimation(int passed_Amount_X, int passed_Amount_Y)
{
Amount_Frame_X = passed_Amount_X;
Amount_Frame_Y = passed_Amount_Y;
}
void Sprite::PlayAnimation(int BeginFrame, int EndFrame, int Row, float Speed)
{
if (animationDelay+Speed < SDL_GetTicks())
{
if (EndFrame <= CurrentFrame)
CurrentFrame = BeginFrame;
else
CurrentFrame++;
crop.x = CurrentFrame * (img_width/Amount_Frame_X);
crop.y = Row * (img_height/Amount_Frame_Y);
crop.w = img_width/Amount_Frame_X;
crop.h = img_height/Amount_Frame_Y;
animationDelay = SDL_GetTicks();
}
}
Sprite::~Sprite()
{
SDL_DestroyTexture(image);
}
void Sprite::SetX(float X)
{
X_pos = X;
rect.x = int(X_pos - Origin_X);
}
void Sprite::SetY(float Y)
{
Y_pos = Y;
rect.y = int(Y_pos - Origin_Y);
}
void Sprite::SetPosition(float X, float Y)
{
X_pos = X;
Y_pos = Y;
rect.x = int(X_pos - Origin_X);
rect.y = int(Y_pos - Origin_Y);
}
float Sprite::getX()
{
return X_pos;
}
float Sprite::getY()
{
return Y_pos;
}
void Sprite::SetOrigin(float X, float Y)
{
Origin_X = X;
Origin_Y = Y;
SetPosition(getX(),getY());
}
void Sprite::SetWidth(int W)
{
rect.w = W;
}
void Sprite::SetHeight(int H)
{
rect.h = H;
}
int Sprite::GetWidth()
{
return rect.w;
}
int Sprite::GetHeight()
{
return rect.h;
}
//header
#pragma once
#include "stdafx.h"
#include "SDL_Setup.h"
#include "CollisionRectangle.h"
class Sprite
{
public:
Sprite(SDL_Renderer* passed_renderer, std::string FilePath, int x, int y, int w, int h, float *CameraX, float *CameraY, CollisionRectangle passed_CollisionRect);
~Sprite();
void Draw();
void DrawSteady();
void SetX(float X);
void SetY(float Y);
void SetPosition(float X, float Y);
float getX();
float getY();
void SetOrigin(float X, float Y);
int GetWidth();
int GetHeight();
void SetHeight(int H);
void SetWidth(int W);
void PlayAnimation(int BeginFrame, int EndFrame, int Row, float Speed);
void SetUpAnimation(int passed_Amount_X, int passed_Amount_Y);
private:
CollisionRectangle CollisionRect;
SDL_Rect Camera;
SDL_Rect CollisionSDL_Rect;
float *CameraX;
float *CameraY;
float Origin_X;
float Origin_Y;
float X_pos;
float Y_pos;
SDL_Texture* image;
SDL_Texture* CollisionImage;
SDL_Rect rect;
SDL_Rect crop;
SDL_Renderer* renderer;
int img_width;
int img_height;
int CurrentFrame;
int animationDelay;
int Amount_Frame_X;
int Amount_Frame_Y;
};