【问题标题】:SFML/C++ cells won't moveSFML/C++ 单元格不会移动
【发布时间】:2020-12-31 19:16:24
【问题描述】:

我目前正在尝试制作元胞自动机。我只是了解方向、运动和渲染的基础知识。 但是,在运行编译器时,尽管调用了 Move 函数,但单元格不会移动。

这是文件,

细胞.cpp

#include "Cell.h"
#include "CellManager.h"

Cell::Cell()
{
    Lifetime = 5 + rand() % 2 - 1;
}

Cell::~Cell()
{
}

void Cell::Move(int dir)
{
    switch (dir)
    {
    default: y -= 2;
        break;
    case 0: y -= 2;
        break;
    case 1: x += 2;
        break;
    case 2: y += 2;
        break;
    case 3: x -= 2;
        break;
    }
    if (x > 800)
    {
        x = 0;
    } else if (x < 0)
    {
        x = 800;
    }   
    if (y > 800)
    {
        y = 0;
    }
    else if (y < 0)
    {
        y = 800;
    }
}

int Cell::ChangeDir(int dir)
{
    dir = rand() % 3;
    return dir;
}

void Cell::Draw(sf::RenderTarget& target)
{
    sf::RectangleShape cell;
    cell.setSize(sf::Vector2f(2.f,2.f));
    cell.setOutlineColor(colour);
    cell.setPosition(x, y);
    target.draw(cell);
}

void Cell::SetUp(int X, int Y, sf::Color Colour, int dir)
{
    x = X;
    y = Y;
    colour = Colour;
    Dir = dir;
}

CellManager.cpp

#include "CellManager.h"
#include "Cell.h"

void CellManager::UpdateCells(vector<Cell> cells, sf::RenderTarget& target)
{
    for (int i = 0; i < cells.size(); i++)
    {
        cells[i].ChangeDir(cells[i].Dir);
        cells[i].Move(cells[i].Dir);
        cells[i].Draw(target);
    }
}

void CellManager::CreateInstance()//TODO
{
}

我不明白我哪里出错了,因为 switch 语句有效,但单元格只是拒绝移动。任何帮助将不胜感激:)

【问题讨论】:

  • 你应该展示你是如何调用CellManager::UpdateCells(vector&lt;Cell&gt; cells,...)的,因为这个函数会创建一个vector的副本,你可能打算不断更新每个Cell,但不要因为你只编辑副本。

标签: c++ function void


【解决方案1】:

您的函数,CellManager::UpdateCell 的参数vector&lt;Cell&gt; cells COPIES 单元格向量,然后更改副本。您可能希望通过引用传递。这看起来像:std::vector&lt;Cell&gt;&amp; cells


其他说明:

ChangeDir 不会改变成员变量 Dir。你也可以通过引用传递,或者根本不传递任何东西并使用Dir = rand() % 3;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-05-09
    • 1970-01-01
    • 2013-06-25
    • 2013-04-17
    • 2017-07-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多