【发布时间】:2020-09-16 06:28:12
【问题描述】:
这是我写的一个代码示例,考虑到封装和组合:
class Bullet {
private:
Vector2 position;
Vector2 speed;
public:
void move(float time_delta) {
position += speed * time_delta;
}
};
基本上,只有一个弹丸在无处移动。但是,子弹实际上可以e。 G。从墙上弹跳,其speed 发生了显着变化。有没有考虑这种相互作用的好方法?我既不想让我的Bullet 知道“高级”类(应该自己使用它),也不想写一个像这样的一次性解决方案:
template<typename F> void move(float time_delta, F collision_checker);
更新:如果您想缩小这个问题的范围,值得一读。下面是移动Bullets(我并不是指Bullet::move() 成员函数!)以及它们与其他实体的交互的期望逻辑的简化示例:
Vector2 destination = bullet.position + bullet.speed * time_delta;
if (std::optional<Creature> target = get_first_creature(bullet.position, destination)) {
// decrease Bullet::speed depending on the target (and calculate the damage)
} else if (std::optional<Wall> obstacle = get_first_wall(bullet.position, destination)) {
// calculate the ricochet changing Bullet::position and Bullet::speed
}
所有由 cmets 表示的代码都应该使用 Creature 和 Wall classes 的某些属性。
【问题讨论】:
-
与对象的交互集由类方法定义。
-
@stark 这是
Bullet类与更高级别的类交互,而不是与Bullet交互的人。 -
这个问题不能只看项目符号来回答。正如您已经意识到的那样,子弹目前在没有任何上下文的情况下无处可去。一种解决方案可能是让
move接受一个附加参数void move(float time_delta, World& world),但可能性太多,您应该着眼于大局而不是考虑单个类 -
@idclev463035818 问题是
World也知道Bullet,不幸的是,您的解决方案给了我一个循环依赖。 -
循环依赖可以解决,但正如我已经说过的,不是只看一个部分
标签: c++ oop aggregation composition design-decisions