Search code examples
javascriptcolorsphysicsjs

How to change color of a circle in PhysicsJS?


I have a cells array of white circles. Every world.step or so, I want to change one random circle to red. I can access and change the color of the circle like this:

var n = Math.floor(Math.random()*100);
cells[n].styles.fillStyle = colors.red;

This works once. Once I call world.step in the Physics.util.ticker.on, no more circles turn red. Here is my complete function:

 Physics.util.ticker.on(function(time) {
     var n = Math.floor(Math.random()*100);
     cells[n].styles.fillStyle = colors.red;
     world.add(cells);
     world.step();
});

I tried the provided suggestion and got this code:

switch (newState) {
    case states.cancerInterphase:
        cells[n].styles.fillStyle = colors.red;
        break;
    case states.cancerMitosis:
        cells[n].styles.fillStyle = colors.pink;
        break;
    case states.interphase:
        cells[n].styles.fillStyle = colors.white;
        break;
    case states.mitosis:
        cells[n].styles.fillStyle = colors.blue;
        break;
}
cells[n].state.vel = new Physics.vector(speed[0], speed[1]);
cells[n].view = null;
world.add(cells);

Eventually, the step function runs and updates the page. Unfortunately, the trace of the old circle is still left behind.

I fixed this issue by using a canvas renderer rather than pixi.js.


Solution

  • The library stores a cached image of the body in body.view, so in order to get it to refresh you'll need to remove that property so the renderer re-draws the image.

    var cell = cells[n];
    cell.styles.fillStyle = colors.red;
    cell.view = null;