【问题标题】:How can my class be provided some information about its environment?如何向我的班级提供有关其环境的一些信息?
【发布时间】: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 表示的代码都应该使用 CreatureWall classes 的某些属性。

【问题讨论】:

  • 与对象的交互集由类方法定义。
  • @stark 这是Bullet 类与更高级别的类交互,而不是与Bullet 交互的人。
  • 这个问题不能只看项目符号来回答。正如您已经意识到的那样,子弹目前在没有任何上下文的情况下无处可去。一种解决方案可能是让move 接受一个附加参数void move(float time_delta, World&amp; world),但可能性太多,您应该着眼于大局而不是考虑单个类
  • @idclev463035818 问题是World 也知道Bullet,不幸的是,您的解决方案给了我一个循环依赖。
  • 循环依赖可以解决,但正如我已经说过的,不是只看一个部分

标签: c++ oop aggregation composition design-decisions


【解决方案1】:

从设计的角度来看,如果您的子弹不知道如何检测它何时...通过障碍物 (scnr),这可能是最好的选择。因此,将Bullet 类转换为struct 可能会更好,即让它表现得像一个被执行的东西而不是被执行的东西。

你仍然可以添加你的便利函数,但让它不可变:

struct Bullet {
  Vector2 position;
  Vector2 speed;
  Vector2 move(float time_delta) const {
    return position + speed * time_delta;
  }
};

这样您就可以从调用范围计算冲突:

auto dest = bullet.move(dt);
while (std::optional<Collision> const col = detectCollision(bullet.position,dest)) {
  bullet.position = col->intersectPoint;
  bullet.speed = col->reflectedSpeed;
  dest = col->reflectDest;
}
bullet.position = dest;

这里detectCollision 检查从子弹当前位置到新位置dest 的线是否与任何障碍物相交并计算反射参数。实际上,您会曲折前往目的地,这将是子弹的所有连续乒乓球与潜在障碍的结果。

【讨论】:

    猜你喜欢
    • 2021-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 2020-05-02
    • 1970-01-01
    相关资源
    最近更新 更多