自定义类的List.Contains的替代方法

时间:2017-06-04 22:28:07

标签: list contains path-finding

我试图用A *进行寻路并制作一个班级" Node"。

关键是我有一个节点列表,我需要知道节点是否已经在列表中,但List.Contains不起作用。

顺便说一句,我需要比较Node内部变量的世界位置,而且我不知道如何覆盖List.Contains以与该变量进行比较。

编辑:添加了尝试实现Equals和HashSet的Node类

using System.Collections;
using UnityEngine;
using System.Collections.Generic;

public class Node {

public Node parentNode;

public int nodeX;
public int nodeY;
public Vector2 nodePosition;

public bool state;

public int gCost;
public int hCost;
public int fCost;

public Node(int x, int y){
    nodeX = Mathf.RoundToInt(x);
    nodeY = Mathf.RoundToInt(y);
    nodePosition = new Vector2(nodeX, nodeY);
}

public void SetCost(Node end){
    if(parentNode != null){
        gCost =(int) parentNode.gCost + 10;
    }
    else{
        gCost = 10;
    }

    hCost =(int) (Mathf.Abs(nodeX - end.nodeX) + Mathf.Abs(nodeY-end.nodeY));
    fCost =(int) gCost + hCost;
}

public bool Equals (Node other){
    if(other == null){return false;}
    if(this.nodePosition == other.nodePosition){return true;}
    else{return false;}

}

public override bool Equals(Object other){
    if(other == null){return false;}
    if(other is Node){
        return this.Equals(other);
    }
    else{
        return false;
    }
}

public override int GetHashCode(){
    return nodeX ^ nodeY;
}

1 个答案:

答案 0 :(得分:0)

对于开放集,您应该使用priority queue。对于封闭集,只需向每个节点添加属性HasBeenVisited即可。您不需要{* 1}来获取A *。