我正在编写一个简单的场景图来保存一些对象,这样我就可以在 OpenGL 中控制这些对象的渲染和绘制。我有两个类,一个称为 GameObject,它定义了具有某些参数的对象,例如位置和速度以及如何绘制对象。它有一个名为 update() 的方法,用于计算位置的任何变化,然后调用 draw() 将自己绘制到屏幕上。
另一个类称为sceneNode。这个类控制我用来存储对象的数据结构。这个类的一个实例包含一个指向 GameObject 实例的指针,以允许我访问数据,并且 sceneNode 具有存储在向量中的 sceneNode 类型的子节点。
每个班级都可以很好地独立工作。我可以将孩子添加到场景图等中,我可以创建一个游戏对象并告诉它自己绘制,一切都按预期工作。
然后我向sceneNode添加了一个名为render()的新方法,该方法获取指向gameObject的指针并在调用节点的任何子节点上的render()之前调用它的更新函数。
问题是:调用了 update() 方法并绘制了游戏对象,但它始终绘制在同一个位置,并且尽管有速度和位置变化,但它不会移动。使用 GameObject 的实例调用 update() 函数会绘制对象并在屏幕上移动对象。我已经盯着这段代码好几个小时了,看不到我错过了什么。我对指针和从另一个类调用方法的想法还很陌生,所以我可能错过了一些明显的东西。
以下是相关方法:
GameObject.cpp:变量位置、速度等被列为受保护。
void GameObject::update(){
for (int i = 0; i<3;i++){
this->velocity[i] +=this->acceleration[i];
}
this->position[0] += this->velocity[0];
this->position[1] += this->velocity[1];
this->position[2] += this->velocity[2];
this->draw();
}
void GameObject::draw() {
glTranslatef(this->position[0], this->position[1], this->position[2]);
glBegin(GL_TRIANGLES);
for (int i = 0; i < this->num_tris; i++) {
for (int j = 0; j <3 ; j++) {
glVertex3fv(vertices[triangles[i].INDEXES[j]]);
}
}
glEnd();
}
场景节点.cpp:
void sceneNode::render(){
GameObject *go = new GameObject();
go = this->data;
//data is the name of the variable storing a pointer to a GameObject
go->update();
//update() is a method that redraws the object and calc's new position etc
if (hasChildren()) { //if this node has children, render all of them aswell...
for (int i = 0; i< this->node_tree.size(); i++) {
this->node_tree.at(i).render();
}
}
sceneNode.h:这是在 sceneNode 中设置 GameObject 指针的方式
Protected:
GameObject* data;
我不知道为什么 render() 方法的位置没有改变,而是 update() 方法的位置没有改变,因为它们都在调用同一个东西?
谢谢你的帮助