CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 10 of 10
  1. #1
    Join Date
    Nov 2016
    Posts
    12

    OpenGL program refuses to enter "for" loop

    Hey all! I've been getting this issue when I'm trying to check for collision against the camera in my game and boxes I've created. For some reason, however, the program refuses to enter the for loop that iterates through the game objects. I've been looking at the code for hours now and I really can't find the issue. Here's the "for" loop in question:

    Code:
    for (vector<Box*>::iterator i = boxes.begin(); i != boxes.end(); ++i)
    	{
    		if ((*i)->getType() == ObjectType::BOX)
    		{
    			if (camera->getPosition().x >= ((*i)->Position.x - (*i)->getXBuffer()) && camera->getPosition().x <= ((*i)->Position.x + (*i)->getXBuffer()))
    			{
    				if (camera->getPosition().z >= ((*i)->Position.z - (*i)->getZBuffer()) && camera->getPosition().z <= ((*i)->Position.z + (*i)->getZBuffer()))		//change to Z axis and get camera position instead of radius
    				{
    					o++;
    					cout << o << endl;
    					collided = true;
    				}
    			}
    		}
    	}
    and here's the main.cpp class. I don't think any or my other classes are effecting this issue:

    Code:
    #include "Font.h"
    #include "ogro.h"
    #include "Box.h"
    #include "md2model.h"
    #include "sstream"
    #include "Camera.h"
    #include "Time.h"
    #include <vector>
    using namespace std;
    
    #include "vgl.h"
    #include <glm/glm.hpp>
    #include <glm/gtc/matrix_transform.hpp>
    #include <glm/gtx/norm.hpp>
    using namespace glm;
    #define SPACEBAR_KEY 32
    #define ESCAPE_KEY 033
    
    Camera* camera;
    Ogro* ogro;
    //Box* boxes;
    Font* font;
    string fontText;
    vector<GameObject*> gameObjects;
    vector<Box * > boxes;
    //vector<Box * > boxes;
    
    int treesTapped = 0, points = 0;
    
    
    float lastTime;
    bool keyDown[255];
    
    void timer(int value)
    {
    	glutPostRedisplay();
    	glutTimerFunc(25, timer, 0);
    }
    
    void closeApp()
    {
    	delete camera;
    	delete font;
    	for (auto it = gameObjects.begin(); it != gameObjects.end(); ++it)
    	{
    		delete (*it);
    	}	
    }
    
    void CheckKeyboard()
    {
    	int o = 0;
    
    	if (keyDown['a'])
    		camera->RotateLeft();
    	if (keyDown['d'])
    		camera->RotateRight();
    	if (keyDown['w'])
    		camera->MoveForward();
    	if (keyDown['s'])
    		camera->MoveBackWard();
    	/*if (keyDown['e'])
    		camera->StrafeRight();
    	if (keyDown['q'])
    		camera->StrafeLeft();*/
    
    	vec3 p = camera->getPosition();
    	camera->Update();
    	bool collided = false;
    
    	for (vector<Box*>::iterator i = boxes.begin(); i != boxes.end(); ++i)
    	{
    		if ((*i)->getType() == ObjectType::BOX)
    		{
    			if (camera->getPosition().x >= ((*i)->Position.x - (*i)->getXBuffer()) && camera->getPosition().x <= ((*i)->Position.x + (*i)->getXBuffer()))
    			{
    				if (camera->getPosition().z >= ((*i)->Position.z - (*i)->getZBuffer()) && camera->getPosition().z <= ((*i)->Position.z + (*i)->getZBuffer()))		//change to Z axis and get camera position instead of radius
    				{
    					o++;
    					cout << o << endl;
    					collided = true;
    				}
    			}
    		}
    	}
    	
    	if (collided)
    	{
    		camera->position = p;
    		camera->Update();
    	}
    
    	if (camera->position.x >= 90.0f)
    	{
    		camera->position.x = 90.0f;
    	}
    	if (camera->position.x <= -90.0f)
    	{
    		camera->position.x = -90.0f;
    	}
    	if (camera->position.z >= 90.0f)
    	{
    		camera->position.z = 90.0f;
    	}
    	if (camera->position.z <= -90.0f)
    	{
    		camera->position.z = -90.0f;
    	}
    
    	srand(time(NULL));
    
    }
    
    float getElapsedSeconds()
    {
    	float currentTime = float(GetTickCount()) / 1000.0f;
    	float seconds = float(currentTime - lastTime);
    	lastTime = currentTime;
    	return seconds;
    }
    
    void keyboardUp(unsigned char key, int x, int y)
    {
    	keyDown[key] = false;
    }
    
    void mouseMovement(int x, int y)
    {
    	static bool warp = true;
    
    	if (warp)
    	{
    		if (x>glutGet(GLUT_WINDOW_WIDTH) / 2)
    			camera->RotateRight();
    		else if (x<glutGet(GLUT_WINDOW_WIDTH) / 2)
    			camera->RotateLeft();
    
    		if (y>glutGet(GLUT_WINDOW_HEIGHT) / 2)
    			camera->RotateUp();
    		else if (y<glutGet(GLUT_WINDOW_HEIGHT) / 2)
    			camera->RotateDown();
    
    		glutWarpPointer(glutGet(GLUT_WINDOW_WIDTH) / 2, glutGet(GLUT_WINDOW_HEIGHT) / 2);
    		warp = false;
    	}
    	else
    		warp = true;
    }
    
    void mouseWheel(int button, int direction, int x, int y)
    {
    
    	if (button == 16)
    		camera->ResetFOV();
    	else if (direction > 0)
    		camera->ZoomIn();
    	else
    		camera->ZoomOut();
    }
    
    void keyboardSpecialKeys(int key, int x, int y)
    {
    	float yaw;
    	switch (key)
    	{
    	case GLUT_KEY_LEFT:
    		yaw = ((Ogro*)gameObjects[1])->getYaw();
    		yaw -= 5.0;
    		((Ogro*)gameObjects[1])->setYaw(yaw);
    		break;
    	case GLUT_KEY_RIGHT:
    		yaw = ((Ogro*)gameObjects[1])->getYaw();
    		yaw += 5.0;
    		((Ogro*)gameObjects[1])->setYaw(yaw);
    		break;
    	}
    }
    
    void keyboard(unsigned char key, int x, int y)
    {
    	keyDown[key] = true;
    	switch (key)
    	{
    	case ESCAPE_KEY:
    		exit(EXIT_SUCCESS);
    		break;
    	case 'e':
    		((Box*)gameObjects[1])->ChangeTexture();
    		treesTapped++;
    		break;
    	}
    	
    }
    
    void display()
    {
    	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
    	CheckKeyboard();
    
    	if (fontText.length() != 0)
    		font->printText(fontText, 350, 550, 25);
    
    	float dt = getElapsedSeconds();
    	for (int i = 0; i <= gameObjects.size() - 1; i++)
    	{
    		switch (gameObjects[i]->getType())
    		{
    		case ObjectType::BOX:
    			((Box*)gameObjects[i])->setMVPMatrix(camera->ViewMatrix, camera->ProjectionMatrix);
    			gameObjects[i]->Draw(dt);
    			break;
    		/*case ObjectType::OGRO:
    			((Ogro*)gameObjects[i])->changeInTime = dt;
    			((Ogro*)gameObjects[i])->Draw(camera->ViewMatrix, camera->ProjectionMatrix);
    			break;*/
    		}
    	}
    
    	std::stringstream ss1;
    	ss1 << "Trees tapped: " << treesTapped;
    	font->printText(ss1.str().c_str(), 20, 550, 15);
    	std::stringstream ss2;
    	ss2 << "Points: " << points;
    	font->printText(ss2.str().c_str(), 20, 520, 15);
    
    
    	glutSwapBuffers();
    }
    
    
    void init()
    {
    	glClearColor(0.0f, 0.0f, 0.7f, 0.0f);
    	glEnable(GL_DEPTH_TEST);
    	glDepthFunc(GL_LESS);
    
    	font = new Font();
    	camera = new Camera();
    	camera->setPosition(vec3(20.0f, 1.5f, 0.0f));
    	glutWarpPointer(glutGet(GLUT_WINDOW_WIDTH) / 2, glutGet(GLUT_WINDOW_HEIGHT) / 2);
    	std::fill(keyDown, keyDown + 255, false);
    
    	gameObjects.push_back(new Box(vec3(0.0f, -2.0f, 0.0f), "data/images/grass-1.png", "data/shaders/Texture.vertexshader", "data/shaders/Texture.fragmentshader", "Data\\Models\\Floor.xml", true, 0.1f, vec3(100.0f, 0.1f, 100.0f), true));
    	gameObjects.push_back(new Box(vec3(0.0f, -2.0f, 0.0f), "data/images/wood.bmp", "data/shaders/Texture.vertexshader", "data/shaders/Texture.fragmentshader", "Data\\Models\\Floor.xml", true, 0.1f, vec3(1.0f, 10.0f, 1.0f), true));
    	gameObjects.push_back(new Box(vec3(0.0f, 6.0f, 0.0f), "data/images/leaves.jpg", "data/shaders/Texture.vertexshader", "data/shaders/Texture.fragmentshader", "Data\\Models\\Floor.xml", true, 0.1f, vec3(2.5f, 2.5f, 2.5f), true));
    
    	/*gameObjects.push_back(new Ogro());
    	((Ogro*)gameObjects[1])->Initialize();
    	((Ogro*)gameObjects[1])->setPosition(vec3(0, 0, 0));
    	((Ogro*)gameObjects[1])->setDirection(vec3(1, 0, 0));
    	((Ogro*)gameObjects[1])->setYaw(90);
    
    	gameObjects.push_back(new Ogro());
    	((Ogro*)gameObjects[2])->Initialize();
    	((Ogro*)gameObjects[2])->setYaw(-90);
    	((Ogro*)gameObjects[2])->setPosition(vec3(0, 0, -3));
    	((Ogro*)gameObjects[2])->setDirection(vec3(1, 0, 0));*/
    }
    
    
    
    int main(int argc, char** argv)
    {
    	glutInit(&argc, argv);
    
    	glutInitDisplayMode(GLUT_RGBA | GLUT_DEPTH);
    	glutInitWindowSize(1024, 768);
    	glutInitContextProfile(GLUT_CORE_PROFILE);
    	glutCreateWindow("Model Example1");
    	
    
    	if (glewInit())
    	{
    		cerr << "Unable to init glew" << endl;
    		exit(EXIT_FAILURE);
    	}
    
    	init();
    	glutDisplayFunc(display);
    	glutKeyboardFunc(keyboard);
    	glutKeyboardUpFunc(keyboardUp);
    	glutSpecialFunc(keyboardSpecialKeys);
    	//glutPassiveMotionFunc(mouseMovement);
    	glutMouseWheelFunc(mouseWheel);
    	glutTimerFunc(25, timer, 0);
    	glutMainLoop();
    	return 0;
    }

  2. #2
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: OpenGL program refuses to enter "for" loop

    For some reason, however, the program refuses to enter the for loop that iterates through the game objects
    Code:
    for (vector<Box*>::iterator i = boxes.begin(); i != boxes.end(); ++i)
    Where are items added to the vector boxes - as this is not in the code posted? If the vector boxes has no elements then the for loop won't be entered.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  3. #3
    Join Date
    Nov 2016
    Posts
    12

    Re: OpenGL program refuses to enter "for" loop

    Quote Originally Posted by 2kaud View Post
    Code:
    for (vector<Box*>::iterator i = boxes.begin(); i != boxes.end(); ++i)
    Where are items added to the vector boxes - as this is not in the code posted? If the vector boxes has no elements then the for loop won't be entered.
    Did I not populate the vector in the Display function? I'm honestly so new to OpenGL and it seems more than a little foreign to me. If I did not, then how could I go about populating the vector so that I could achieve what I set out to do? Thank you so much, I really appreciate it!!

  4. #4
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: OpenGL program refuses to enter "for" loop

    Did I not populate the vector in the Display function?
    It doesn't look like it.

    I'm trying to check for collision against the camera in my game and boxes I've created
    Also I don't see any code that actually creates boxes? Apart from the definition of the variable boxes and the for statement, no other posted code refers to boxes?
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  5. #5
    Join Date
    Nov 2016
    Posts
    12

    Re: OpenGL program refuses to enter "for" loop

    Quote Originally Posted by 2kaud View Post
    It doesn't look like it.



    Also I don't see any code that actually creates boxes? Apart from the definition of the variable boxes and the for statement, no other posted code refers to boxes?
    There are two classes that are used to make boxes.

    Box.cpp

    Code:
    #include "Box.h"
    
    
    
    void Box::setPosition(vec3 position)
    {
    	Position = position;
    	TranslationMatrix = translate(glm::mat4(1.0f), Position);
    }
    
    
    Box::Box(vec3 initialPosition, const char* imagePath, const string vertexShader, const string fragmentShader, char* modelPath, bool m, float sp, vec3 s, bool vis) :GameObject(vertexShader, fragmentShader)
    {
    	Position = initialPosition;
    	vertexBufferData = VertexBufferData(modelPath);
    	scaleVector = s;
    	speed = sp/250;
    	master = m;
    	Visible = vis;
    	radius = (s.x + s.y + s.z) / 3;
    
    	direction = vec3(0.0f, 0.0f, 0.0f);
    	Hit = false;
    	rotationAngle = 0.0f;
    
    	RotationMatrix = mat4(1.0f);
    	OrbitMatrix = mat4(1.0f);
    	ScaleMatrix = mat4(1.0f);
    
    	ScaleMatrix = glm::scale(mat4(1.0f), scaleVector);
    	TranslationMatrix = glm::translate(mat4(1.0f), Position);
    
    	if (!shaderProgram->initialize())
    	{
    		std::cerr << "Could not initialize the shaders" << std::endl;
    	}
    
    	shaderProgram->bindShader();
    
    	glGenVertexArrays(1, &vertexBufferData.VAO);
    	glBindVertexArray(vertexBufferData.VAO);
    
    	printf("Reading image %s\n", imagePath);
    	int img_width, img_height, channels;
    	unsigned char *img = SOIL_load_image(imagePath, &img_width, &img_height, &channels, 0);
    	glGenTextures(1, &vertexBufferData.Texture);
    	glBindTexture(GL_TEXTURE_2D, vertexBufferData.Texture);
    	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
    	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
    	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img);
    	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
    	glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
    
    	glGenBuffers(1, &vertexBufferData.elementBuffer);
    	glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertexBufferData.elementBuffer);
    	glBufferData(GL_ELEMENT_ARRAY_BUFFER, vertexBufferData.elementSize, &vertexBufferData.elements[0], GL_STATIC_DRAW);
    
    	glGenBuffers(1, &vertexBufferData.vertexBuffer);
    	glBindBuffer(GL_ARRAY_BUFFER, vertexBufferData.vertexBuffer);
    	glBufferData(GL_ARRAY_BUFFER, vertexBufferData.verticiesSize, &vertexBufferData.verticies[0], GL_STATIC_DRAW);
    
    	glGenBuffers(1, &vertexBufferData.textbuffer);
    	glBindBuffer(GL_ARRAY_BUFFER, vertexBufferData.textbuffer);
    	glBufferData(GL_ARRAY_BUFFER, vertexBufferData.texcoordSize, &vertexBufferData.texcoords[0], GL_STATIC_DRAW);
    }
    
    
    void Box::Draw(float deltaTime)
    {
    	if (Visible)
    	{
    		Position += direction * deltaTime * speed;
    		shaderProgram->bindShader();
    		glBindVertexArray(vertexBufferData.VAO);
    
    		int size;
    		glGetBufferParameteriv(GL_ELEMENT_ARRAY_BUFFER, GL_BUFFER_SIZE, &size);
    
    		glBindTexture(GL_TEXTURE_2D, vertexBufferData.Texture);
    		shaderProgram->sendUniform("TextureSampler", 0);
    
    		shaderProgram->sendUniform4x4("MVP", glm::value_ptr(MVP));
    
    		glEnableVertexAttribArray(0);
    		glEnableVertexAttribArray(1);
    
    		glBindBuffer(GL_ARRAY_BUFFER, vertexBufferData.vertexBuffer);
    		glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
    
    		glBindBuffer(GL_ARRAY_BUFFER, vertexBufferData.textbuffer);
    		glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 0, BUFFER_OFFSET(0));
    
    		glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertexBufferData.elementBuffer);
    
    		glDrawElements(GL_TRIANGLES, size / sizeof(GLushort), GL_UNSIGNED_SHORT, 0);
    
    		glDisableVertexAttribArray(0);
    		glDisableVertexAttribArray(1);
    	}
    	
    }
    
    
    void Box::OnCollide(Box *box)
    {
    	if (master)//you are the master cube
    	{
    		/*We do nothing if we are the master cube*/
    		return;
    	}
    	else if (box->master)//hit the master cube
    	{
    		Hit = true;
    	}
    	else//hit another small cube
    	{
    		direction.x = -direction.x;
    		direction.y = direction.y;
    	}
    }
    
    bool Box:: operator!=(Box b)
    {
    	if (Position != b.Position)
    		return  true;
    	else
    		return false;
    }
    
    float Box::getXBuffer()
    {
    	return  2 * scaleVector.x;
    }
    
    float Box::getYBuffer()
    {
    	return  2 * scaleVector.y;
    }
    
    float Box::getZBuffer()
    {
    	return  2 * scaleVector.z;
    }
    
    void Box::setMVPMatrix(mat4 viewMatrix, mat4 projectionMatrix)
    {
    	MVP = projectionMatrix * viewMatrix * getModelMatrix();
    }
    
    void Box::setScaleMatrix(vec3 scale)
    {
    	scaleVector = scale;
    	ScaleMatrix = glm::scale(mat4(1.0f), scaleVector);
    }
    
    void Box::setTranslationMatrix(vec3 pos)
    {
    	Position = pos;
    	TranslationMatrix = glm::translate(glm::mat4(1.0f), Position);
    }
    
    void Box::setRotationMatrix(float angle, float x, float y, float z)
    {
    	RotationMatrix = glm::rotate(mat4(1.0f), angle, vec3(x, y, z));
    }
    
    void Box::setOrbitMatrix(vec3 pos, float angle, float x, float y, float z)
    {
    	OrbitMatrix = glm::rotate(glm::translate(glm::mat4(1.0f), pos), angle, vec3(x, y, z));
    }
    
    void Box::ChangeTexture()
    {
    	int img_width, img_height, channels;
    	unsigned char *img = SOIL_load_image("data/images/metal.bmp", &img_width, &img_height, &channels, 0);
    	glBindTexture(GL_TEXTURE_2D, vertexBufferData.Texture);
    	glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, img_width, img_height, 0, GL_RGB, GL_UNSIGNED_BYTE, img);
    }
    and Box.h

    Code:
    #pragma once
    #include "GameObject.h"
    #include "md2model.h"
    
    class Box : public GameObject
    {
    
    private:
    	mat4 MVP;
    	mat4 ModelMatrix;
    	mat4 RotationMatrix;
    	mat4 OrbitMatrix;
    	mat4 TranslationMatrix;
    	mat4 ScaleMatrix;
    
    public:
    	void Draw(float deltaTime);
    	void OnCollide(Box * box);
    	virtual ObjectType getType() const { return BOX; }
    
    	mat4 getModelMatrix() { return getOrbitMatrix()*getTranslationMatrix()* getRotationMatrix()*getScaleMatrix(); }
    
    	mat4 getTranslationMatrix() { return translate(glm::mat4(1.0f), Position); }
    	mat4 getRotationMatrix() { return RotationMatrix; }
    	mat4 getScaleMatrix() { return ScaleMatrix; }
    	mat4 getOrbitMatrix() { return OrbitMatrix; }
    	vec3 getPosition(){ return Position; }
    
    
    	void setOrbitMatrix(vec3 pos, float angle, float x, float y, float z);
    	void setRotationMatrix(float angle, float x, float y, float z);
    	void setScaleMatrix(vec3 scale);
    	void setTranslationMatrix(vec3 pos);
    	void setMVPMatrix(mat4 viewMatrix, mat4 projectionMatrix);
    
    	bool Visible;
    	void ChangeTexture();
    	bool operator!=(Box b);
    	float getXBuffer();
    	float getYBuffer();
    	float getZBuffer();
    
    	void setPosition(vec3 position);
    
    	Box(vec3 initialPosition, const char* imagePath, const string vertexShader, const string fragmentShader, char* modelPath, bool m, float sp, vec3 s, bool vis);
    
    	vec3 Position;
    	vec3 direction;
    	vec3 scaleVector;
    	float rotationAngle;
    	bool Hit;
    	bool master;
    	float speed;
    	float radius;
    	
    };
    I'm not sure if either of these files populates the vector, however. I guess I just thought that vectors were populated because the boxes do get drawn to the screen, but just without the collision that I need.

  6. #6
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: OpenGL program refuses to enter "for" loop

    I'm not sure if either of these files populates the vector, however. I guess I just thought that vectors were populated because the boxes do get drawn to the screen
    That is the code for the class Box. It can't populate the boxes vector as the boxes vector is defined within your code and isn't passed as a parameter to any function.

    it look like the vector gameObjects is being populated with addresses of Box objects. Try changing
    Code:
    for (vector<Box*>::iterator i = boxes.begin(); i != boxes.end(); ++i)
    to

    Code:
    for (auto i = gameObjects.begin(); i != gameObjects.end(); ++i)
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  7. #7
    Join Date
    Nov 2016
    Posts
    12

    Re: OpenGL program refuses to enter "for" loop

    Quote Originally Posted by 2kaud View Post
    That is the code for the class Box. It can't populate the boxes vector as the boxes vector is defined within your code and isn't passed as a parameter to any function.

    it look like the vector gameObjects is being populated with addresses of Box objects. Try changing
    Code:
    for (vector<Box*>::iterator i = boxes.begin(); i != boxes.end(); ++i)
    to

    Code:
    for (auto i = gameObjects.begin(); i != gameObjects.end(); ++i)
    So I actually gave this a shot in the past, but the line
    Code:
    if (camera->getPosition().x >= ((*i)->Position.x - (*i)->getXBuffer()) && camera->getPosition().x <= ((*i)->Position.x + (*i)->getXBuffer()))
    and

    Code:
    if (camera->getPosition().z >= ((*i)->Position.z - (*i)->getZBuffer()) && camera->getPosition().z <= ((*i)->Position.z + (*i)->getZBuffer()))
    gets a whole bunch of errors because the X, Y, and Z locations of the boxes that I need collision for are set in the Box.cpp and Box.h classes, not the GameObject.cpp and GameObject.h classes. Is there any way I can work around this? It sounds like it might be a little counter-productive to rewrite both classes to get the positions from the other class, but I could be wrong. Again, I really appreciate all the help, you're really helping me make more sense of this.

  8. #8
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: OpenGL program refuses to enter "for" loop

    Class Box is derived from class GameObject. So consider
    Code:
    	for (auto i = gameObjects.begin(); i != gameObjects.end(); ++i)
    	{
    		if ((*i)->getType() == ObjectType::BOX)
    		{
    			auto b = (Box*)*i;
    			if (camera->getPosition().x >= (b->Position.x - b->getXBuffer()) && camera->getPosition().x <= (b->Position.x + b->getXBuffer()))
    			{
    				if (camera->getPosition().z >= (b->Position.z - b->getZBuffer()) && camera->getPosition().z <= (b->Position.z + b->getZBuffer()))		//change to Z axis and get camera position instead of radius
    				{
    					o++;
    					cout << o << endl;
    					collided = true;
    				}
    			}
    		}
    	}
    as the function getType() is virtual.
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  9. #9
    Join Date
    Nov 2016
    Posts
    12

    Re: OpenGL program refuses to enter "for" loop

    Quote Originally Posted by 2kaud View Post
    Class Box is derived from class GameObject. So consider
    Code:
    	for (auto i = gameObjects.begin(); i != gameObjects.end(); ++i)
    	{
    		if ((*i)->getType() == ObjectType::BOX)
    		{
    			auto b = (Box*)*i;
    			if (camera->getPosition().x >= (b->Position.x - b->getXBuffer()) && camera->getPosition().x <= (b->Position.x + b->getXBuffer()))
    			{
    				if (camera->getPosition().z >= (b->Position.z - b->getZBuffer()) && camera->getPosition().z <= (b->Position.z + b->getZBuffer()))		//change to Z axis and get camera position instead of radius
    				{
    					o++;
    					cout << o << endl;
    					collided = true;
    				}
    			}
    		}
    	}
    as the function getType() is virtual.
    That works! It enters the loop now, which is amazing! Unfortunately, it restricts camera movement upon loading, but I feel like I know why.

    So the reason what you suggested I do works is because you cast the gameObject i as a box? Do you think you could explain that to me just so I know why what I was doing was wrong? Thank you so much, you have now idea how much I appreciate this!!

  10. #10
    2kaud's Avatar
    2kaud is offline Super Moderator Power Poster
    Join Date
    Dec 2012
    Location
    England
    Posts
    7,824

    Re: OpenGL program refuses to enter "for" loop

    When run, does the code reach the 2nd if statement - ie is the getType() returing ObjectType::BOX?

    Box is derived from GameObject and gameObjects is a vector of pointers to GameObject. As Box is dereived from GameObject, gameObjects can store pointers to Box. So when iterating the gameObjects vector if the item is a BOX pointer then the pointer can be cast to a BOX pointer which is what b type is - a pointer to BOX. getType() is virtual so the class is polymorphic for this function.

    See http://www.learncpp.com/cpp-tutorial...rived-objects/
    All advice is offered in good faith only. All my code is tested (unless stated explicitly otherwise) with the latest version of Microsoft Visual Studio (using the supported features of the latest standard) and is offered as examples only - not as production quality. I cannot offer advice regarding any other c/c++ compiler/IDE or incompatibilities with VS. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/ and can be used without reference or acknowledgement. Also note that I only provide advice and guidance via the forums - and not via private messages!

    C++23 Compiler: Microsoft VS2022 (17.6.5)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured