Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

Help on improving enemy movement?

Discussion in '2D' started by Camden9, Apr 20, 2020.

  1. Camden9

    Camden9

    Joined:
    Feb 25, 2020
    Posts:
    2
    Hello, I’m very new to programming but I’m trying to make a simple 2d top down shooter game and my player character is moves by pressing wasd so it can only move in 8 directions and I want the enemy to also have the same movement (so that it could only move up, down, left, and right + diagonals) I currently am moving the enemy with MoveTowards but it lets the enemy move in a full 360° of movement and I don’t really like that. If anyone has any advice, I would really appreciate it, I can post my code if it could help but it is extremely simple so I figured it wasn’t necessary.
     
  2. Derekloffin

    Derekloffin

    Joined:
    Mar 14, 2018
    Posts:
    322
    You'll have to do a bit more advanced path finding. Assuming still full float space, just only allowing 8 directional movement (as apposed to tiled space), you want to program it such that the enemies choose a diagonal movement until they are on the same x/y as the player, then they use a straight horizontal/vertical movement. There will be some issue with some rounding I suspect as you won't usually get exact matches in the x/y coordinates so you probably want to give them a bit of a range (like +/-.01) before the switch to direct movement. You'll have to experiment with the range to see what looks good. You could also add a bit of a 'fudge' move that once you get within the range, you force the mob to exactly match the x/y of the player, but I don't think that will be necessary.

    So, using an example:
    Say your mob is at 10, 5.7 and your player is at 3, 1.2. Both X and Y are different and outside the allowable range so diagonal movement is needed. So first get the diff with something like Vector2 diff = playerPos - mobPos;
    Then figure out which is smaller magnitude, x or y, in this case it would be the Y as that is 1.2 - 5.7 or -4.5 compared to -7 on the X. Make a new vector that is the smaller value in both x and y so it is exactly diagonal (so -4.5, -4.5), normalize and adjust for your speed and move in that direction until you get a matching x/y within the range. Once you match you switch to direct vector to the player.

    This will have to be reevaluated constantly as obviously your player is moving too, so little point in generating a destination point.
     
    Camden9 likes this.
  3. Camden9

    Camden9

    Joined:
    Feb 25, 2020
    Posts:
    2
    Thank you this makes a lot of sense, I’m going to try to implement this and see if I can make it work!