【问题标题】:Breakout game - Collision detection突围游戏 - 碰撞检测
【发布时间】:2014-04-23 17:59:28
【问题描述】:

我正在使用适用于 Windows 8 的 DirectXTK 库用 C++ 编写一个 Breakout 游戏,但在矢量内的 Ball 和 Brick 对象之间的碰撞检测方面遇到了一些问题。 Ball类负责与桨和砖的碰撞检测。它有一个 Update 方法,该方法在其声明中引用了 Paddle 对象和 Brick 对象。现在与桨的碰撞工作得很好,因为桨是在主游戏类中声明的,但我不知道如何引用存储在向量中的对象。顺便说一句,如果我从 Ball::Update 方法声明中删除“Brick&brick”,则会按预期绘制 5 行积木。

球更新类

void Ball::Update(float timeDelta, Rect windowBounds, Paddle& paddle, Brick& brick)
{

//Respond to collision with the Paddle
if ( paddle.IntersectsWith(this->boundingBox))
{
    this->velocity.y = this->velocity.y * -1;
}

// Respond to collision with the brick
if (brick.IntersectsWith(this->boundingBox))
{
    this->velocity.y = this->velocity.y * -1;
    brick.Hit();
    this->score+= 10;
}
}

这是在 Game 类中初始化 Brick 对象的方式,bricksRow 是向量

//Next, create this many Brick objects and store them in a std::vector
for (int j = 0; j < bricksNumberOfRows; j+=32)
{
    for ( int i = 0; i < numberOfBricks ; i++)
    {
        //Add a Brick object to the back of the vector
        this->bricksRow.push_back(Brick());
        //Get a local reference to this newly added Brick object
        Brick& brick = this->bricksRow.back();
        //Call the initialise method on the newly added Brick object
        brick.Initialize(L"Assets/Brick.png"
            , this->d3dDevice
            , this->d3dDeviceContext
            , Vector2((float)(i * this->brickWidth), bricksStartingPosition + j));
    }
}

在 Game 类中调用 ball.Update 方法

 this->ball.Update(timeDelta, this->windowBounds, this->paddle, ******* );

星星在哪里,我应该在向量中引用 Brick& 对象,但我不知道如何。

感谢您提前回复。

【问题讨论】:

  • 您想要的是对存储砖的向量的引用:void Ball::Update(..., (std::vector&lt;Brick&gt;)&amp; bricks)
  • 这样我就不能在 Ball 类中调用 Brick 类的方法了。

标签: c++ windows-8


【解决方案1】:

您可能想要检测桨与向量中每个砖块对象的碰撞,因此您可以像这样枚举并调用 Update():

vector<Brick>::iterator ci;
for(ci = bricksRow.begin(); ci! = bricksRow.end(); ci++)
{
    this->ball.Update(timeDelta, this->windowBounds, this->paddle, *ci);
}

如果您知道要检测碰撞的砖对象的索引(假设它存储在变量 index 中),则可以如下调用:

this->ball.Update(timeDelta, this->windowBounds, this->paddle, bricksRow[index]);

更新:迭代器应该是iterator而不是const_iterator,所以不是

vector<Brick>::const_iterator ci;

应该是

vector<Brick>::iterator ci;

更好的是,因为您没有修改 void Ball::Update(float timeDelta, Rect windowBounds, Paddle& paddle, Brick&brick) 内的对象 brick,如果您可以改成 void Ball::Update(float timeDelta, Rect windowBounds, Paddle& paddle, const Brick&brick),那么就可以保留

vector<Brick>::const_iterator ci;

对差异的解释可能值得一个单独的问题。以上内容可能会帮助您解决当前遇到的问题。

【讨论】:

  • 我想检测球与矢量中每个砖块对象的碰撞,我认为这就是您在回答中的意思。无论如何,我在 *ci is this->ball.Update(timeDelta, this->windowBounds, this->paddle, *ci);它说 Error: qualifiers dropped in binding reference of type “Brick &” to initialize of type “const Brick”
  • 使用迭代器,ball.Update 会被调用很多次,并且球会每秒更新很多次。我相信每次迭代器遍历向量时它都会更新,这一直是。感谢您抽出宝贵的时间凯文。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多