Path Following Algorithm for Entity











up vote
1
down vote

favorite












Within my game there are many entities, where each entity has a path (Array<Vector2>) assigned to it. No path to follow (indicating that the entity should move at all) is indicated by an empty path (the path is never null). updateMoveAttributes is called every frame for every entity, so it is important that it is efficient.



Note that my entity's direction is in radians, ranging from - Math.PI to Math.PI, since this is what Math.atan2 returns.



The below snippet contains updateMoveAttributes and its supporting methods.



private final Array<Vector2> path = new Array<>();
private int pathIndex = 0;

private static final float EPSILON = 1e-3f;

private float getXDifference(Vector2 pathComponent) {
float xDifference = pathComponent.x - getSprite().getX();

xDifference = Math.abs(xDifference) < EPSILON ? 0 : xDifference;

return xDifference;
}

private float getYDifference(Vector2 pathComponent) {
float yDifference = pathComponent.y - getSprite().getY();

yDifference = Math.abs(yDifference) < EPSILON ? 0 : yDifference;

return yDifference;
}

public float orient(Vector2 pathComponent) {
float xDiff = getXDifference(pathComponent);
float yDiff = getYDifference(pathComponent);

return (float) Math.atan2(yDiff, xDiff);
}

void updateMoveAttributes() {
// No path assigned
if (getPath().size == 0)
return;

// No more path to travel
if (getPathIndex() == getPath().size) {
setSpeed(0);

return;
}

Vector2 nextPathComponent = getPath().get(getPathIndex());
float angleToComponent = orient(nextPathComponent);

setDirection(angleToComponent);

float xDiff = getXDifference(nextPathComponent);
float yDiff = getYDifference(nextPathComponent);

boolean angleInPositiveXQuadrants = (-Math.PI / 2 <= angleToComponent && angleToComponent <= Math.PI / 2);
boolean pastX = angleInPositiveXQuadrants ? (xDiff <= 0) : (xDiff >= 0);

boolean angleInPositiveYQuadrants = (0 <= angleToComponent) && (angleToComponent <= Math.PI);
boolean pastY = angleInPositiveYQuadrants ? (yDiff <= 0) : (yDiff >= 0);

// Indicates that we have passed the path component we are on route to, adjust course with respect
// to next available path component.
if (pastY && pastX)
setPathIndex(getPathIndex() + 1);

// In case user upgrades entity during travel of entity -> movement speed changes -> update required for actual speed
setSpeed(getMovementSpeed());
}

public Array<Vector2> getPath() {
return path;
}









share|improve this question


























    up vote
    1
    down vote

    favorite












    Within my game there are many entities, where each entity has a path (Array<Vector2>) assigned to it. No path to follow (indicating that the entity should move at all) is indicated by an empty path (the path is never null). updateMoveAttributes is called every frame for every entity, so it is important that it is efficient.



    Note that my entity's direction is in radians, ranging from - Math.PI to Math.PI, since this is what Math.atan2 returns.



    The below snippet contains updateMoveAttributes and its supporting methods.



    private final Array<Vector2> path = new Array<>();
    private int pathIndex = 0;

    private static final float EPSILON = 1e-3f;

    private float getXDifference(Vector2 pathComponent) {
    float xDifference = pathComponent.x - getSprite().getX();

    xDifference = Math.abs(xDifference) < EPSILON ? 0 : xDifference;

    return xDifference;
    }

    private float getYDifference(Vector2 pathComponent) {
    float yDifference = pathComponent.y - getSprite().getY();

    yDifference = Math.abs(yDifference) < EPSILON ? 0 : yDifference;

    return yDifference;
    }

    public float orient(Vector2 pathComponent) {
    float xDiff = getXDifference(pathComponent);
    float yDiff = getYDifference(pathComponent);

    return (float) Math.atan2(yDiff, xDiff);
    }

    void updateMoveAttributes() {
    // No path assigned
    if (getPath().size == 0)
    return;

    // No more path to travel
    if (getPathIndex() == getPath().size) {
    setSpeed(0);

    return;
    }

    Vector2 nextPathComponent = getPath().get(getPathIndex());
    float angleToComponent = orient(nextPathComponent);

    setDirection(angleToComponent);

    float xDiff = getXDifference(nextPathComponent);
    float yDiff = getYDifference(nextPathComponent);

    boolean angleInPositiveXQuadrants = (-Math.PI / 2 <= angleToComponent && angleToComponent <= Math.PI / 2);
    boolean pastX = angleInPositiveXQuadrants ? (xDiff <= 0) : (xDiff >= 0);

    boolean angleInPositiveYQuadrants = (0 <= angleToComponent) && (angleToComponent <= Math.PI);
    boolean pastY = angleInPositiveYQuadrants ? (yDiff <= 0) : (yDiff >= 0);

    // Indicates that we have passed the path component we are on route to, adjust course with respect
    // to next available path component.
    if (pastY && pastX)
    setPathIndex(getPathIndex() + 1);

    // In case user upgrades entity during travel of entity -> movement speed changes -> update required for actual speed
    setSpeed(getMovementSpeed());
    }

    public Array<Vector2> getPath() {
    return path;
    }









    share|improve this question
























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      Within my game there are many entities, where each entity has a path (Array<Vector2>) assigned to it. No path to follow (indicating that the entity should move at all) is indicated by an empty path (the path is never null). updateMoveAttributes is called every frame for every entity, so it is important that it is efficient.



      Note that my entity's direction is in radians, ranging from - Math.PI to Math.PI, since this is what Math.atan2 returns.



      The below snippet contains updateMoveAttributes and its supporting methods.



      private final Array<Vector2> path = new Array<>();
      private int pathIndex = 0;

      private static final float EPSILON = 1e-3f;

      private float getXDifference(Vector2 pathComponent) {
      float xDifference = pathComponent.x - getSprite().getX();

      xDifference = Math.abs(xDifference) < EPSILON ? 0 : xDifference;

      return xDifference;
      }

      private float getYDifference(Vector2 pathComponent) {
      float yDifference = pathComponent.y - getSprite().getY();

      yDifference = Math.abs(yDifference) < EPSILON ? 0 : yDifference;

      return yDifference;
      }

      public float orient(Vector2 pathComponent) {
      float xDiff = getXDifference(pathComponent);
      float yDiff = getYDifference(pathComponent);

      return (float) Math.atan2(yDiff, xDiff);
      }

      void updateMoveAttributes() {
      // No path assigned
      if (getPath().size == 0)
      return;

      // No more path to travel
      if (getPathIndex() == getPath().size) {
      setSpeed(0);

      return;
      }

      Vector2 nextPathComponent = getPath().get(getPathIndex());
      float angleToComponent = orient(nextPathComponent);

      setDirection(angleToComponent);

      float xDiff = getXDifference(nextPathComponent);
      float yDiff = getYDifference(nextPathComponent);

      boolean angleInPositiveXQuadrants = (-Math.PI / 2 <= angleToComponent && angleToComponent <= Math.PI / 2);
      boolean pastX = angleInPositiveXQuadrants ? (xDiff <= 0) : (xDiff >= 0);

      boolean angleInPositiveYQuadrants = (0 <= angleToComponent) && (angleToComponent <= Math.PI);
      boolean pastY = angleInPositiveYQuadrants ? (yDiff <= 0) : (yDiff >= 0);

      // Indicates that we have passed the path component we are on route to, adjust course with respect
      // to next available path component.
      if (pastY && pastX)
      setPathIndex(getPathIndex() + 1);

      // In case user upgrades entity during travel of entity -> movement speed changes -> update required for actual speed
      setSpeed(getMovementSpeed());
      }

      public Array<Vector2> getPath() {
      return path;
      }









      share|improve this question













      Within my game there are many entities, where each entity has a path (Array<Vector2>) assigned to it. No path to follow (indicating that the entity should move at all) is indicated by an empty path (the path is never null). updateMoveAttributes is called every frame for every entity, so it is important that it is efficient.



      Note that my entity's direction is in radians, ranging from - Math.PI to Math.PI, since this is what Math.atan2 returns.



      The below snippet contains updateMoveAttributes and its supporting methods.



      private final Array<Vector2> path = new Array<>();
      private int pathIndex = 0;

      private static final float EPSILON = 1e-3f;

      private float getXDifference(Vector2 pathComponent) {
      float xDifference = pathComponent.x - getSprite().getX();

      xDifference = Math.abs(xDifference) < EPSILON ? 0 : xDifference;

      return xDifference;
      }

      private float getYDifference(Vector2 pathComponent) {
      float yDifference = pathComponent.y - getSprite().getY();

      yDifference = Math.abs(yDifference) < EPSILON ? 0 : yDifference;

      return yDifference;
      }

      public float orient(Vector2 pathComponent) {
      float xDiff = getXDifference(pathComponent);
      float yDiff = getYDifference(pathComponent);

      return (float) Math.atan2(yDiff, xDiff);
      }

      void updateMoveAttributes() {
      // No path assigned
      if (getPath().size == 0)
      return;

      // No more path to travel
      if (getPathIndex() == getPath().size) {
      setSpeed(0);

      return;
      }

      Vector2 nextPathComponent = getPath().get(getPathIndex());
      float angleToComponent = orient(nextPathComponent);

      setDirection(angleToComponent);

      float xDiff = getXDifference(nextPathComponent);
      float yDiff = getYDifference(nextPathComponent);

      boolean angleInPositiveXQuadrants = (-Math.PI / 2 <= angleToComponent && angleToComponent <= Math.PI / 2);
      boolean pastX = angleInPositiveXQuadrants ? (xDiff <= 0) : (xDiff >= 0);

      boolean angleInPositiveYQuadrants = (0 <= angleToComponent) && (angleToComponent <= Math.PI);
      boolean pastY = angleInPositiveYQuadrants ? (yDiff <= 0) : (yDiff >= 0);

      // Indicates that we have passed the path component we are on route to, adjust course with respect
      // to next available path component.
      if (pastY && pastX)
      setPathIndex(getPathIndex() + 1);

      // In case user upgrades entity during travel of entity -> movement speed changes -> update required for actual speed
      setSpeed(getMovementSpeed());
      }

      public Array<Vector2> getPath() {
      return path;
      }






      java performance game coordinate-system libgdx






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jul 8 at 20:44









      Mar Dev

      26229




      26229






















          1 Answer
          1






          active

          oldest

          votes

















          up vote
          0
          down vote














          1. Method getXDifference and getYDifference are very similar, you can convert this into a single method that accepts two variables.

          2. you could also inline the return statement as the method name is sufficient to tell what it is returning.


          3. Instead of calculating pastX and pastY, you can write methods to return the computed value.



            boolean isPastX(variables...){
            // logic to calculate pastX and return it.
            }


            and the if statement will turn into if( isPastX() && isPastY()).
            This will also help in short-circuiting the condition in case calculating pastX or pastY is very expensive(it isn't in this example, just a suggestion).




          4. Curly braces {} should always be used after conditional statements or loops, even it's just a single line. It may avoid confusion in some scenarios.



            if (getPath().size == 0){
            return;
            }







          share|improve this answer





















            Your Answer





            StackExchange.ifUsing("editor", function () {
            return StackExchange.using("mathjaxEditing", function () {
            StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
            StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
            });
            });
            }, "mathjax-editing");

            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "196"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            convertImagesToLinks: false,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: null,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f198103%2fpath-following-algorithm-for-entity%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes








            up vote
            0
            down vote














            1. Method getXDifference and getYDifference are very similar, you can convert this into a single method that accepts two variables.

            2. you could also inline the return statement as the method name is sufficient to tell what it is returning.


            3. Instead of calculating pastX and pastY, you can write methods to return the computed value.



              boolean isPastX(variables...){
              // logic to calculate pastX and return it.
              }


              and the if statement will turn into if( isPastX() && isPastY()).
              This will also help in short-circuiting the condition in case calculating pastX or pastY is very expensive(it isn't in this example, just a suggestion).




            4. Curly braces {} should always be used after conditional statements or loops, even it's just a single line. It may avoid confusion in some scenarios.



              if (getPath().size == 0){
              return;
              }







            share|improve this answer

























              up vote
              0
              down vote














              1. Method getXDifference and getYDifference are very similar, you can convert this into a single method that accepts two variables.

              2. you could also inline the return statement as the method name is sufficient to tell what it is returning.


              3. Instead of calculating pastX and pastY, you can write methods to return the computed value.



                boolean isPastX(variables...){
                // logic to calculate pastX and return it.
                }


                and the if statement will turn into if( isPastX() && isPastY()).
                This will also help in short-circuiting the condition in case calculating pastX or pastY is very expensive(it isn't in this example, just a suggestion).




              4. Curly braces {} should always be used after conditional statements or loops, even it's just a single line. It may avoid confusion in some scenarios.



                if (getPath().size == 0){
                return;
                }







              share|improve this answer























                up vote
                0
                down vote










                up vote
                0
                down vote










                1. Method getXDifference and getYDifference are very similar, you can convert this into a single method that accepts two variables.

                2. you could also inline the return statement as the method name is sufficient to tell what it is returning.


                3. Instead of calculating pastX and pastY, you can write methods to return the computed value.



                  boolean isPastX(variables...){
                  // logic to calculate pastX and return it.
                  }


                  and the if statement will turn into if( isPastX() && isPastY()).
                  This will also help in short-circuiting the condition in case calculating pastX or pastY is very expensive(it isn't in this example, just a suggestion).




                4. Curly braces {} should always be used after conditional statements or loops, even it's just a single line. It may avoid confusion in some scenarios.



                  if (getPath().size == 0){
                  return;
                  }







                share|improve this answer













                1. Method getXDifference and getYDifference are very similar, you can convert this into a single method that accepts two variables.

                2. you could also inline the return statement as the method name is sufficient to tell what it is returning.


                3. Instead of calculating pastX and pastY, you can write methods to return the computed value.



                  boolean isPastX(variables...){
                  // logic to calculate pastX and return it.
                  }


                  and the if statement will turn into if( isPastX() && isPastY()).
                  This will also help in short-circuiting the condition in case calculating pastX or pastY is very expensive(it isn't in this example, just a suggestion).




                4. Curly braces {} should always be used after conditional statements or loops, even it's just a single line. It may avoid confusion in some scenarios.



                  if (getPath().size == 0){
                  return;
                  }








                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jul 9 at 2:25









                Ankit Soni

                481111




                481111






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Code Review Stack Exchange!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    Use MathJax to format equations. MathJax reference.


                    To learn more, see our tips on writing great answers.





                    Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                    Please pay close attention to the following guidance:


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f198103%2fpath-following-algorithm-for-entity%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Сан-Квентин

                    8-я гвардейская общевойсковая армия

                    Алькесар