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. Dismiss Notice

Autopath on certain points

Discussion in 'Scripting' started by ArjanforGames, Sep 19, 2014.

  1. ArjanforGames

    ArjanforGames

    Joined:
    Mar 25, 2014
    Posts:
    1
    Hello,

    I have a question.
    I got a topdown view 'city' with all straight streets. Think of them like + (crossing) and - (normal street).
    Now, I want a cube to move from a point to another point I clicked on. So, then the cube will move, following all defined points.

    I drew something to explain it better:


    Greets,
    Arjan
     
  2. JoeStrout

    JoeStrout

    Joined:
    Jan 14, 2011
    Posts:
    9,840
    This is called "pathfinding." The commonly chosen algorithm for this is A* (pronounced "A-star"), and is described here.

    If you're an intermediate level programmer or better, implementing A* is a good exercise — it only works out to a couple pages of code, and it's a very handy tool to have in your toolbox. If not, well, if you wait long enough @TwixEmma will probably write it for you. :) (Just teasing, Emma — I think it's awesome that you're so helpful to everyone!)

    I have a couple of A* implementations lying around, but they're fairly specific to some unique things I was doing in those projects, so they wouldn't readily drop into your app.

    But also note that A* could well be overkill... if your city really is a regular grid, with no closed streets, then you don't need to do anything complicated. Simply step from each point to whichever neighboring point is closest to the goal. That'll do it.

    Or, even if you do have obstacles, here's another algorithm, which in some cases is even better than A* (like when you have lots of agents moving around, and only a few goals, and the navigation paths don't change often): make a map of how far each node is from the goal. You can easily do this with a recursive algorithm, where you set the distance of neighboring points only if their distance isn't already set, and then recurse. Now, any agent can move to the goal simply by stepping to whichever neighbor is closest to the goal, by that measure.

    There are other tricks too that apply in only certain circumstances... if you have a budget for some consulting work, feel free to PM me and I'm sure I can craft a solution that works great for your game.
     
    BmxGrilled likes this.
  3. BmxGrilled

    BmxGrilled

    Joined:
    Jan 27, 2014
    Posts:
    238
    lol.