首页 > 解决方案 > 如何比较列表中两个类属性的两个数据?

问题描述

嘿伙计们,我正在创建一个即时游戏,需要一些帮助。检查玩家是否踩到地图位置的最佳方法是什么?这是我的课:

class MapInfo
{
    public int PosX { get; set; }
    public int PosY { get; set; }
    public int Terrain { get; set; }
}

class PlayerInfo
{
    public int PosX { get; set; }
    public int PosY { get; set; }
}

做这个的最好方式是什么?我尝试为 KnownPlaces 创建一个列表,但是如果我尝试执行 foreach 并比较从玩家位置到地图位置的值,我不知道如何只搜索一次相等的值。

标签: c#unity3d

解决方案


根据我对您的问题的理解;2个类,其中一个用于查询另一个的历史,这是您需要做的。

高层总结:

您需要有一个存储位置信息的类 ( MapInfo)。这些位置的过去记录需要存储在某个地方 ( KnownPlaces)。然后您需要记录您当前的位置 ( PlayerInfo),并使用它来查询已知地点列表。如果没有匹配,您将需要创建并存储新记录。

在我的示例中,我为您提供了所有这些类的框架。但是,何时添加新位置、何时​​查询它们等等的逻辑取决于您。因为你是游戏的创造者。

class MapInfo
{
    public int PosX { get; set; }
    public int PosY { get; set; }
    public int Terrain { get; set; }
    public bool alreadyVisited { get; set; }

    // Anything else you want to record
    // … … 
}

class PlayerInfo
{
    public int currentPosX { get; set; }
    public int currentPosY { get; set; }
    public MapInfo currentMapInfo { get; set; }

    public void getCurrentMapInfo()
    {
       currentMapInfo = KnownPlaces.GetMapInfo(currentPosX, currentPosY);
    }
}

public class KnownPlaces 
{
    public static List<MapInfo> AllKnownPlaces = new List<MapInfo>();

    public static MapInfo GetMapInfo(int posX, int posY)
    {
      MapInfo place = KnownPlaces.AllKnownPlaces.FirstOrDefault(n => n.PosX == posX && n.PosY == posY);
      return place;
    }

    Public static void CreateNewMapInfo(int posX, int posY, //… other stuff you want to record)
    {
       MapInfo newMapInfo = new MapInfo();
       newMapInfo.PosX = posX;
       newMapInfo.PosY = posY;
       // Anything else that you want to record.

       KnownPlaces.AllKnownPlaces.Add(newMapInfo);
    }   
}

推荐阅读