2
\$\begingroup\$

so i've been making a pathfinder on a grid. I've succesfuly implemented the A* algorithm so the next step is making the AI follow a path. I got it to move to the desired destination but the thing is it moves diagonally and I dont want it to. I want to move vertically or horizontally. this is my current code:

void AIEnemy::AutoMotion(Gridspot& grid)

{

std::pair<int, int> ecn = getNodePosition();

sf::Time deltaTime = clock.getElapsedTime();

std::reverse(grid.Path.begin(), grid.Path.end());

for (auto path : grid.Path)

{

float rectx = rect.getPosition().x + rect.getOrigin().x / 2,

        `recty = rect.getPosition().y + rect.getOrigin().y / 2;`
bool firm= true;



if (ecn.first == path.node.first && top >= path.rectCenter.y)

{

rect.move(0, -2);



}



if (ecn.second == path.node.second && left >= path.rectCenter.x)

{

rect.move(-2 , 0);



}

}



}

before i had a bool set that will ring true it is already in motion to so that it couldn't move in the x-axis in conjunction to th y. that didn't work, i also used if and elseif is before ut that didn't do anything. essentially I want it to move like pacman ghosts

enter image description here

\$\endgroup\$
1
\$\begingroup\$

What you need to do is, once you begin moving in one direction, make it impossible to to move in another direction until you complete the movement. It would look something like this in psuedocode:

if (!moveableObject.isMoving()) {
    if (pathIsOpenUp()) {
        moveableObject.setTrajectoryUp();
    }
    else if (pathIsOpenLeft()) {
        moveableObject.setTrajectoryLeft();
    }
    // Repeat for bottom and right
}

Now your trajectory function needs to persist between frames and your isMoving() flag needs to be cleared and trajectory zero'd out when the end of a path is reached.

\$\endgroup\$
4
  • \$\begingroup\$ thank you. that's another workaround i thought would work too ( and I think it will work) but i don't know how to detect speed/movement in sfml or I guess \$\endgroup\$ Apr 21 '19 at 0:19
  • \$\begingroup\$ @YamaraiAkizuki it's an implementation detail. You use collision detection to determine if it is too close to an edge and if so stop movement. \$\endgroup\$
    – Summer
    Apr 21 '19 at 0:41
  • \$\begingroup\$ isMoving() is just a Boolean flag: mMoving or some such. When you setTrajectory you flip it true. And when it gets closer to the edge you clear it false. \$\endgroup\$
    – Summer
    Apr 21 '19 at 0:43
  • \$\begingroup\$ I used the boolean flags and everything but nothing changed. im guessing im not checking the right thing \$\endgroup\$ Apr 22 '19 at 12:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.