c# - 基于winforms中的鼠标单击查找到对象的最短距离

标签 c# .net winforms

我在使此功能正常工作时遇到问题。我必须创建一个充当出租车映射器的 winform 应用程序。加载时,出租车会根据文本文件放置在同一位置。当用户点击表格时,最近的出租车应该移动到“用户”或位置,然后停下来。

除了最近的出租车并不总是到达该位置外,一切正常。较远的出租车将前往该地点。它似乎有时有效,但并非一直有效。我不确定我的逻辑在 Form1_MouseDown 函数中是否正确

private void Form1_MouseDown(object sender, MouseEventArgs e)
{
    if (pickUp) //Are we picking up a passenger?
    {
        //Convert mouse pointer location to local window locations
        int mLocalX = this.PointToClient(Cursor.Position).X;
        int mLocalY = this.PointToClient(Cursor.Position).Y;

        //set the minimum value (for range finding)
        int min = int.MaxValue;
        //Temporary object to get the handle for the taxi object we want to manipulate
        taxiCabTmp = new TaxiClass();

        //Iterate through each object to determine who is the closest
        foreach (TaxiClass taxiCab in taxi)
        {
            if (Math.Abs(Math.Abs(taxiCab.CabLocationX - mLocalX) + Math.Abs(taxiCab.CabLocationY - mLocalY)) <= min)
            {
                min = Math.Abs(Math.Abs(taxiCab.CabLocationX - mLocalX) + Math.Abs(taxiCab.CabLocationY - mLocalY));
                //We found a minimum, grab a handle to the object's instance
                taxiCab.GetReference(ref taxiCabTmp);
            }
        }
        //Call the propogate method so it can spin off a thread to slowly change it's location for the timer to also change
        taxiCabTmp.Propogate(mLocalX - 20, mLocalY - 20);
        taxiCabTmp.occupied = true; //This taxi object is occupied
        pickUp = false; //We are not picking up a passenger at the moment
    }
    else //We are dropping off a passenger
    {
        taxiCabTmp.Propogate(this.PointToClient(Cursor.Position).X, this.PointToClient(Cursor.Position).Y);
        taxiCabTmp.occupied = false;
        pickUp = true; //We can pick up a passenger again!
    }
}

最佳答案

您是正确的,您用于确定距离的计算并不总是正确的。倾斜的物体会计算出比实际距离更远。

查看此链接以获取更多信息:http://www.purplemath.com/modules/distform.htm

这是一个例子:

int mLocalX = 1;
int mLocalY = 1;
int taxiCab.CabLocationX = 2;
int taxiCab.CabLocationY = 2;

double distance = Math.Sqrt(Math.Pow((taxiCab.CabLocationX - mLocalX), 2) + Math.Pow((taxiCab.CabLocationY - mLocalY), 2));

作为旁注,您不应该在类后附加 Class,即 TaxiClass,它应该简单地称为 Taxi。

关于c# - 基于winforms中的鼠标单击查找到对象的最短距离,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36763720/

相关文章:

c# - 获取 IList 中项目的值?

.net - 为什么这个通用转换会失败?

c# - 在保存时格式化文档,在 vscode 上删除未使用的使用

c# - Winforms - 在面板内填充用户控件

c# - 使用 DataSource 在 DataGridView 中显示 XML 数据

c# - 如何在 DataGridView 中添加一列(复选框)

c# - 找出调用 DateTime.ToString( ) 时获得的 DateTimeFormat

.net - 如何测量用于 .NET 远程处理的 IP 端口的输入/输出字节数?

vb.net - 对 FlowLayoutPanel 上的按钮进行排序

c# - 锁和互斥锁有什么区别?