SFML/C++ 细胞不会移动

SFML/C++ cells won't move

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

这是文件,

Cell.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::UpdateCell 的参数 vector<Cell> cells COPIES 单元格向量,然后更改副本。您可能想通过引用传递。这看起来像:std::vector<Cell>& cells.


其他说明:

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