我正在尝试实现一个行为树,并且在其组成功能方面苦苦挣扎。基本上,我需要Tick()
在下面实现以调用由嵌入位置定义的方法。
这里是behavior.go
:
type IBehavior interface {
Tick() Status
Update() Status
}
type Behavior struct {
Status Status
}
func (n *Behavior) Tick() Status {
fmt.Println("ticking!")
if n.Status != RUNNING { n.Initialize() }
status := n.Update()
if n.Status != RUNNING { n.Terminate(status) }
return status
}
func (n *Behavior) Update() Status {
fmt.Println("This update is being called")
return n.Status
}
这是Behavior
嵌入的结构:
type IBehaviorTree interface {
IBehavior
}
type BehaviorTree struct {
Behavior
Root IBehavior
}
func (n *BehaviorTree) Update() Status {
fmt.Printf("Tree tick! %#v\n", n.Root)
return n.Root.Tick()
}
使该示例更有意义的一些文件:
type ILeaf interface {
IBehavior
}
type Leaf struct {
Behavior
}
还有这个:
type Test struct {
Leaf
Status Status
}
func NewTest() *Test {
return &Test{}
}
func (n Test) Update() Status {
fmt.Println("Testing!")
return SUCCESS
}
这是其用法示例:
tree := ai.NewBehaviorTree()
test := ai.NewTest()
tree.Root = test
tree.Tick()
我期望通过打印以下内容使树正常打勾:
ticking!
Tree tick!
但是相反,我得到了:
ticking!
This update is being called
有人可以帮我解决这个问题吗?
编辑:添加了一些额外的文件来阐明问题。另外,我不理解反对意见。我有一个老实的问题。我是否只应该问已经对我有意义的问题?
您的问题Tick()
是未在BehaviorTree结构上定义。结果,当您调用时tree.Tick()
,没有定义直接方法,因此它将调用Tick()
嵌入式Behavior
结构的提升方法。该Behavior
结构不知道a BehaviorTree
是什么!在Go的伪继承嵌入样式中,“子”类型没有“父”的概念,也没有引用或访问它们的方式。嵌入式方法是使用嵌入式类型作为其接收方而不是嵌入式结构来调用的。
如果希望获得预期的行为,则需要Tick()
在BehaviorTree
类型上定义一个方法,并让该方法调用其自己的Update()
方法(然后根据需要调用子方法Tick()
或Update()
方法)。例如:
type BehaviorTree struct {
Behavior
Root IBehavior
}
func (n *BehaviorTree) Tick() Status {
n.Update() // TODO: do you want this status or the Root.Tick() status?
return n.Root.Tick()
}
func (n *BehaviorTree) Update() Status {
fmt.Printf("Tree tick! %#v\n", n.Root)
return nil
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句