Question

I'm trying to find a programming concept of representing the orientation of an object on a grid, but my logic is seriously failing me here. If I have Robot (R) and he's facing North, I want him to turn left and right and change orientation accordingly. Obviously this needs to be in a loop (possibly a circular linked list) with regards to if R is facing West but I turn right then R needs to be back facing North.

I've seen this answer Position and orientation of robot in a grid and I have already done something similar using an array, but it doesn't seem right. There must be a better way of doing it.

Looking this up on Google just gives me oriented programming links or really complicated robotics design papers.

Thanks in advance!

Était-ce utile?

La solution 2

The way to do this would be through an enum, similar to the way you would style days of the week. They're in a loop of some sort, and you can map the associated chars with the enum options.

public enum CardinalPosition {
    NORTH('N'), EAST('E'), SOUTH('S'), WEST('W)

    private CardinalPosition left;
    private CardinalPosition right;

    // here you set each left and right per enum value
    private void setupRight() {
        NORTH.right = CardinalPosition.EAST;
        ...
        WEST.right = CardinalPosition.NORTH;
    }

    private void setupLeft() {
        EAST.left = CardinalPosition.NORTH;
        ...
        NORTH.left = CardinalPosition.WEST;
    }

    // so the rotateLeft and rotateRight would just return the left and right values of the given CardinalPosition

}

Autres conseils

Since you don't ask your question for a specific language I can suggest a oo-pseudocode version of what I would do:

class Orientation2d
{
   int direction = 0;
   static Position2d[4] move = { {0,1}, {1,0}, {-1,0}, {-1,-1} };

   void left()
   {
       direction = (direction+4-1) % 4;
   }
   void right()
   {
       direction = (direction+1) % 4;
   }
   Pose2d forward()
   {
      return move[ direction ];
   }
}

class Pose2d
{
   Position2d pos;
   Orientation2d or;

   void moveForward()
   {
       pos += or.forward();
   }
   void turnLeft()
   {
       or.left();
   }
   void turnRight()
   {
       or.right();
   }
}

You should easily be able to convert this to C++ or Java.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top