'How to simulate velocity in a falling sand game?

I'm creating a falling sand game and would like to implement velocity so elements can travel in different directions at varying speeds. Games such as Noita use this and it smoothens out the movement of the elements.

I have a 2d array and shift the elements around the 2d array to move them.

I've looked around and I can't find anything on this. I've gotten so far using line calculations but I'm curious as to the best method of handling this.

Another thing to consider is that if the velocity is small I still want to slowly move the elements. However if the velocity is 0.01 then it will always round down to zero and never move the element to another position.

My elements are stored in a 2d array so the calculated positions must always be integers.

Array

Element[] elements = new Element[1000][1000];

Element

class Element {
    // Array position
    int x, y; 

    Vector2 velocity = new Vector2();

    public Element(int x, int y){
        this.x = x;
        this.y = y;
    }
    ...
}

How can I implement velocity in a falling sand game?



Solution 1:[1]

You could store the velocity as floats, and keep the actual positions as floats as well:

class Element {
    // Array position
    int x, y; 
    
    // actual position
    float fx, fy;
    
    // velocity
    float vx, vy;
    
    public Element(int x, int y){
        this.x = x;
        this.y = y;
    }
    
    public void setVelocity(float vx, float vy) {
        this.vx = vx;
        this.vy = vy;
    }
    
    public void move() {
        // apply velocity
        this.fx += this.vx;
        this.fy += this.vy;
        
        // place position in integer matrix
        this.x = (int) fx;
        this.y = (int) fy;
    }
}

public class Test {
    public static void main(String args[]) {
        Element e = new Element(10, 10);
        e.setVelocity(0.1f, 0.2f);
      
        for (int step =0; step < 100; step++) {
            e.move();    
            System.out.println(String.format("Step: %d x: %d y: %d", step, e.x, e.y));
        }
    }
}

Solution 2:[2]

I'm working on a sand game myself. I think we can just create a new element type particle (besides sand and water) which can have velocity and direction.

sand can turn into a particle when certain conditions are met, for example, when it got blew by wind or spashed by other entities. particles will travel in the grid using its own logic. Again, when certain conditions are met, such as hitting something, the particle turns back to sand.

Let me know how it works out!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 augustzf
Solution 2 mye