So, I’m trying to code a train simulation, where my train ( composed of locomotives and wagons) moves on a railway, but I’m struggling with motion ( or movement?) handling. The code is too long to be put here all at once, but I will provide the function that moves the trains :
function moveTrains(contexte, matrice, plateau) {
let trains = get_trains(plateau); //gets us a list of the available trains on the board
let plateau_init = new Plateau();
cree_plateau_initial(plateau_init); // i made this variable to keep track of the old board before the trains were put, so when the trains move away, i can restore the spot to where it was
for (let train of trains) {
let x = train.x;
let y = train.y;
let direction = Direction.right; //it shouldn't be right always, but for now this isn't the problem
let nouvelle_position = direction.avancer(x, y); //avancer is the french for move forward, it just updates the coordinates according to the direction
let avant = Direction.gauche.avancer(x,y); //gauche is left, which means i'm trying to go back to the previous box or spot
let avant_x = avant.x;
let avant_y= avant.y;
let nouvelle_case_x = nouvelle_position.x; // new position coordinates
let nouvelle_case_y = nouvelle_position.y;
console.log(plateau.cases[x][y]); //debug
if (
nouvelle_case_x >= 0 && nouvelle_case_x < LARGEUR_PLATEAU &&
nouvelle_case_y >= 0 && nouvelle_case_y < HAUTEUR_PLATEAU &&
plateau.cases[nouvelle_case_x][nouvelle_case_y] !== Type_de_case.Foret
) { // console.log(plateau.cases[avant_x][avant_y]);
// here starts the problem
if (plateau.cases[avant_x][avant_y] != Type_de_case.wagon) //if the previous box is not a wagon we free it, putting whatever original rail was there
AjouterObjet(plateau, x, y, plateau_init.cases[x][y]); //ajouterobjet is a function that adds objects
AjouterObjet(plateau, nouvelle_case_x, nouvelle_case_y, plateau.cases[x][y]); //we update the next spot by advancing our locomotive or wagon
plateau.cases[nouvelle_case_x][nouvelle_case_y] = train.type; //update the type pf the box
train.x = nouvelle_case_x;
train.y = nouvelle_case_y;
} else {
}
}
dessine_plateau(contexte, plateau); //just to draw everything
when I start the simulation, the train moves on click but the trains in older positions don’t get erased, so it just keep on duplicating, i tried handling this recursively by moving each unit individually but there is always a problem.