Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
560 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 Answer

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;.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...