Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
561 views
in Technique[技术] by (71.8m points)

function - SFML/C++ cells won't move

I am currently trying to make a cellular automata. I am just getting the basics of direction, movement and rendering. However, when running the compiler the cells don't move despite calling the Move function.

Here are the files,

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
{
}

I do not understand where I am going wrong as the switch statement works but the cells just refuse to move. Any help would be appreciated :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Your function, CellManager::UpdateCell's parameter vector<Cell> cells COPIES the vector of cells, then changes the copies. You probably want to pass by reference instead. This would look like: std::vector<Cell>& cells.


Other note:

ChangeDir does not change the member variable Dir. You could pass in by reference for that as well, or just not pass in anything at all and use Dir = rand() % 3;.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...