0
\$\begingroup\$

I’m working on a 2d game in unity. Right now I’m trying to make a follow ai. Where a character will follow the position of the player. I currently have it set it and working using the MoveTowards function. But my problem is that my game does not use diagonal movement. Wondering if there’s a way to constrain the move towards function to not use diagonals or if there is a better function to use in this instance? Thanks

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

Moving on a single axis is just incrementing the value of the relevant axis in the position vector by the relevant distance. So just do (pseudo code here, because I'm not near my Unity machine)

if (shouldMoveOnX(followerPos, myPos) {
  followerPos.x += step;
} else {
  followerPos.y += step;
}

The only question is how to determine 'shouldMoveOnX' - and in order to fill that function, you need to answer game logic questions such as whether there are blocking objects or other traversal circumstances that should be taken into account. If there aren't, this should be sufficient - it just moves on the axis that has the shorter distance:

bool shouldMoveOnX(Vec3 followerPos, Vec3 myPos) {
  return followerPos.x - myPos.x < followerPos.y - myPos.y;
}
\$\endgroup\$

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.