我开始在我的Java/OpenGL项目中使用具有位置组件的基本实体/对象实现分层场景图,并且知道它们的父实体和子实体。
public class Entity
{
private Entity parent;
private ArrayList<Entity> children = new ArrayList<Entity>();
private Vector3f pos = new Vector3f(0,0,0); //simplified transformation
addChild(Entity child){...}
setParent(Entity parent){...}
public Vector3f getPos(){ return pos; }
public void setPos(Vector3f pos){this.pos = pos}
//this is my non-functional attempt at creating hierarchical movement
public void setRelativePos(Vector3f pos)
{
this.setPos(parent.getPos().add(pos)); //position relative to parent
for(Entity child : children)
{
//how the child relatives to the newly moved parent
vec3 relativePos = child.getPos().sub(getPos());
child.setRelativePos(relativePos);
}
}
}
我想到的是,当父元素的位置被改变/设置时,子元素将相对于父元素移动。
从你所描述的,我认为当你移动一个实体,你想要移动所有的孩子。
您的递归没有停止条件,并且可能导致堆栈溢出。它还有一个令人困惑的名字,setPos
,这意味着一个简单的setter,但这不是它所做的。每种类型的移动事件都应该有不同的方法。例如:平移、旋转等…
你应该这样做:
// simple setter
public void setPos(Vector3f pos)
{
this.pos = pos;
}
// translation movement
public void translate(Vector3f delta)
{
// translate the current Entity
setPos (getPos().add(delta));
// translate the children
for (Entity child : children)
child.translate (delta);
}