Skip to content

Instantly share code, notes, and snippets.

@digiwombat
Last active April 18, 2024 06:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save digiwombat/49234fb43f16e15f1e07e28331947cc7 to your computer and use it in GitHub Desktop.
Save digiwombat/49234fb43f16e15f1e07e28331947cc7 to your computer and use it in GitHub Desktop.
Graph Penalty Setter for AStar
using UnityEngine;
using Pathfinding;
[Pathfinding.Util.Preserve]
public class GraphPenaltySetter : GridGraphRule
{
public LayerMask _layerMask;
public int penalty = 10000;
public override void Register(GridGraphRules rules)
{
if (_layerMask.value == 0)
{
_layerMask = LayerMask.GetMask("Foreground");
}
rules.AddMainThreadPass(Pass.BeforeConnections, context => {
var nodePositions = context.data.nodePositions;
var nodePenalties = context.data.nodePenalties;
GraphCollision gc = new GraphCollision();
gc.use2D = context.graph.collision.use2D;
gc.type = context.graph.collision.type;
gc.collisionCheck = context.graph.collision.collisionCheck;
gc.mask = _layerMask;
gc.diameter = context.graph.collision.diameter;
for (int i = 0; i < nodePositions.Length; i++)
{
if (!gc.Check(nodePenalties[i]))
{
nodePenalties[i] = (uint)penalty;
}
}
});
}
}
using System.Collections.Generic;
using UnityEditor;
using UnityEngine;
using System.Linq;
using Pathfinding;
[CustomGridGraphRuleEditor(typeof(GraphPenaltySetter), "Graph Penalty Setter")]
public class GraphPenaltySetterEditor : IGridGraphRuleEditor
{
public void OnInspectorGUI (GridGraph graph, GridGraphRule rule)
{
var target = rule as GraphPenaltySetter;
GUILayout.BeginHorizontal();
target._layerMask = EditorGUILayoutx.LayerMaskField("", target._layerMask);
target.penalty = EditorGUILayout.IntField(target.penalty);
GUILayout.Space(5);
GUILayout.EndHorizontal();
}
public void OnSceneGUI (GridGraph graph, GridGraphRule rule) { }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment