Peter
Peter

Reputation: 173

Random Path generation in a game

I want to make a 2D game that generates a frequent random paths between two points on the 2D screen. I have read into the A* algorithm + random obstacle generation to create paths but that algorithm seems a bit time-consuming to learn.

My question is "What are the other types of random path generation algorithms that are appropriate for my situation?" ( Generating random paths between 2 fixed points)

Upvotes: 1

Views: 1575

Answers (1)

Immersive
Immersive

Reputation: 1704

Simplest solution I can think of is to generate waypoint nodes that know which other nodes they're connected to, and then randomly choose a connection to follow (possibly with some heuristic to head towards your goal)

eg,

using System.Linq;
public class Waypoint : MonoBehaviour{
    public Waypoint[] Connections;

    public Waypoint Next( Waypoint previous, Waypoint finalDestination) {

        if (this == finalDestination) return null; // You have arrived

        var possibleNext = Connections.Where(m => m != previous && CheckHeuristic(m, finalDestination)); // Dont go backwards, and apply heuristic

        if (possibleNext.Count() == 0) throw new System.ApplicationException("No exitable paths from Waypoint"); // Error if no paths available

        possibleNext = possibleNext.OrderBy( m => Random.Range(0f, 1f)); // 'shuffle'

        return possibleNext.First(); // Grab first 'random' possible path
    }

    private bool CheckHeuristic(Waypoint candidate, Waypoint finalDestination) {
        // Basic 'is not farther' check
        return Vector3.Distance(candidate.transform.position, finalDestination.transform.position) <= Vector3.Distance(this.transform.position, finalDestination.transform.position);
    }
}

Also, "there's no such thing as a free lunch" applies here. There's always a cost to building stuff like this. You'll either spend the time learning A*, or you'll spend the time manually creating paths...

Upvotes: 4

Related Questions