Basic movement and timing

This example illustrates how to write a node algorithm that:

Our new class is called MovingNode.

import io.jbotsim.core.Node;

public class MovingNode extends Node{
    @Override
    public void onStart(){
        setDirection(Math.random()*2*Math.PI);
    }
    @Override
    public void onClock(){
        move(1);
        wrapLocation();
    }
}

Before testing your algorithm, do not forget to register this class as Default Node Model.

Explanations

Another option for moving a node is to call setLocation() with given coordinates (works in 2D or 3D). Depending on the cases, one might prefer one or the other. Note that setDirection() will cause the icon of the node to rotate.

Movement Specification

Movements can be specified in many ways. In this example, we set an initial direction; then the node moves by one unit in this direction in each round. Method move() could also take an argument, specifying the distance to be moved (equivalent to speed). Method wrapLocation() re-locates the node in a toroidal fashion when it gets out of bounds.

Next tutorial: Message Passing vs Graph Algorithms

When designing a node algorithm, an important question is what communication primitives a node can use. In the Message Passing vs Graph Algorithms tutorial, we review the different levels of abstraction that an algorithm can use in JBotSim.