【问题标题】:Hierarchy of Transformations, recursive function troubles转换的层次结构,递归函数的麻烦
【发布时间】:2014-07-25 18:47:15
【问题描述】:

我开始在我的 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);
    }
  }

}

我的想法是,当父母的位置改变/设置时,孩子将相对于他们的父母移动。

【问题讨论】:

  • 也许我在这里误解了一些东西,但是......并不是以场景图的形式拥有层次结构的全部意义,您必须将转换应用于父母(并且孩子将“跟随”而不明确设置转换)?顺便说一句:您应该考虑将转换存储为 4x4 矩阵,否则在执行多个转换(旋转、平移、缩放...)时会遇到麻烦
  • 这就是我第一个设置的方式,但是我也想尝试用这种稍微不同的方法来设置。我在我的项目中使用了一个转换矩阵,但对于这个例子,我认为这会分散实际问题的注意力。 (即非功能递归 setPos)
  • 也许这归结为一个问题,孩子的“位置”是在相对与父位置的坐标中指定的,还是绝对的(在世界坐标中)。但据我了解,你的问题现在已经解决了,所以也许已经无所谓了。

标签: java recursion graph transform hierarchy


【解决方案1】:

根据您的描述,我认为当您移动一个实体时,您想要移动它的所有子级。

您的递归没有停止条件,可能会导致堆栈溢出。 它还有一个令人困惑的名称,setPos,这意味着一个简单的 setter,但这不是它的作用。对于每种类型的 movevent,您应该有不同的方法。例如:平移、旋转等...

你应该这样做:

// 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);
}

【讨论】:

  • 你说得对,我很抱歉我在尝试简化代码命名时搞砸了命名。你很幸运地注意到了这一点。然而,“翻译”功能并不能正确移动孩子,这是我真正需要帮助理解的。
  • @Watercycle translate 会将每个子实体移动相同的 delta 作为父实体。我以为这就是你想要的。
猜你喜欢
  • 2021-02-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-11-22
  • 2017-02-04
  • 1970-01-01
  • 2011-12-23
  • 2010-11-13
相关资源
最近更新 更多