0

I am creating a simulation of a crowd using Java Swing and Java Graphics2D. I have a certain number of pedestrians that must reach some waypoints and I am having troubles with their motion. The movement of each pedestrian now is very simple, it is something like this:

if (goalPosition.x > pedestrian.position.x) {
        pedestrian.position.x++;
    }
    else
        pedestrian.position.x--;

    if (goalPosition.y > pedestrian.position.y) {
        pedestrian.position.y++;
    }
    else
        pedestrian.position.y--;

I just increase/decrease by 1 the position of each pedestrian according to the position of the goal to reach. The problem is that i need to make them walk towards the goal in a straight line, I tried to compute angles and use trigonometry, but the problem with that approach is that I can't update the position of a pedestrian using a double value, because later each pedestrian is drawn using:

g2D.fillOval(pedestrian.position.x, pedestrian.position.y, ENTITY_SIZE, ENTITY_SIZE);

That accepts only integer positions. Any idea of how I can update my code? Thanks

Jimmynera
  • 1
  • 1
  • 1
    Compute positions as double or float, then convert them to integer using `Math.round` – peterz Aug 19 '22 at 08:30
  • Your question basically boils down two things. Find the path between two points and, animate an object along that path, simular to something like [this](https://stackoverflow.com/questions/72411743/how-to-move-paint-graphics-along-slope/72412859#72412859) and [this](https://stackoverflow.com/questions/26784303/java-move-image-towards-mouse-position/26791886#26791886) – MadProgrammer Aug 19 '22 at 08:54
  • Also, you are not restricted to drawing an oval with `fillOval`: you can also [paint `Shape`s](https://docs.oracle.com/en/java/javase/18/docs/api/java.desktop/java/awt/Graphics2D.html#fill(java.awt.Shape)) (like an [`Ellipse2D.Float`](https://docs.oracle.com/en/java/javase/18/docs/api/java.desktop/java/awt/geom/Ellipse2D.Float.html)). – gthanop Aug 19 '22 at 12:21
  • You can make your life much easier and satisfying using OGL/JOGL instead of Swing. Swing was created to be cross-platform toolkit. OGL works with many programming languages and is much easier to create custom graphics and animations in – ControlAltDel Aug 19 '22 at 13:55

0 Answers0