HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Updating positions of enemies every frame

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
positionsupdatingeveryenemiesframe

Problem

I am making a game for Android using Java and libGdx. I have an ArrayList of enemies that are updated each frame. The update method for the enemy looks like this:

public void update(float delta){

    if (waypointIndex < waypointCount){
        waypoint = path.getPoints().get(waypointIndex);

        distanceToWaypointX = waypoint.getX() - getCenterX();
        distanceToWaypointY = waypoint.getY() - getCenterY();

        directionToWaypoint = (float) Math.atan2(distanceToWaypointY, distanceToWaypointX);
        setRotation((float) Math.toDegrees(directionToWaypoint) - 180);

        translationX = (float) (Math.cos(directionToWaypoint) * getMovementSpeed() * delta);
        translationY = (float) (Math.sin(directionToWaypoint) * getMovementSpeed() * delta);

        distanceToWaypoint = (float) Math.hypot(distanceToWaypointX, distanceToWaypointY);

        if (distanceToWaypoint <= 5){
            waypointIndex++;
        }

        distanceTraveled += Math.sqrt(Math.pow(translationX, 2) + Math.pow(translationY, 2));

        translate(translationX, translationY);

    }
}


This works OK, but with 100 enemies the FPS starts to dip into the low 50's. I would like to keep a consistent 60 FPS and I plan to have more than 100 enemies on the screen at a time. How can i improve this code to make it more efficient?

Solution

Some things you could try:

Unless the waypoints change position, the objects will continue in the same direction each frame. This means

  • you don't have to recalculate directionToWaypoint (unless you have imperfect rotation). This includes cos(directionToWaypoint) and sin(directionTpWaypoint)



  • translationX and translationY become simple multiplication



  • distanceTravelled seems too complicated. Why isn't it just getMovementSpeed() * delta?

Context

StackExchange Code Review Q#155204, answer score: 6

Revisions (0)

No revisions yet.