こうかな?
Vector2 pos = P.OrderBy(a => Vector2.Distance(Q, a)).FirstOrDefault();
テスト用コード
csharp
1using System.Collections.Generic;
2using UnityEngine;
3using System.Linq;
4
5public class LinqTest : MonoBehaviour
6{
7 Vector2[] m_positionArray;
8 [SerializeField] Vector2 m_startPosition = Vector2.zero;
9
10 void Start()
11 {
12 // ランダムな座標を生成する
13 List<Vector2> v2List = new List<Vector2>();
14 for (int i = 0; i < 10; i++)
15 {
16 float x = Random.Range(-10f, 10f);
17 float y = Random.Range(-10f, 10f);
18 Vector2 v = new Vector2(x, y);
19 v2List.Add(v);
20 }
21 m_positionArray = v2List.ToArray();
22 }
23
24
25
26
27 public void Calc()
28 {
29 Vector2 positionForMinimumDistance = m_positionArray.OrderBy(p => Vector2.Distance(m_startPosition, p)).FirstOrDefault();
30 Debug.LogFormat("position: {0}, distance: {1}", positionForMinimumDistance.ToString(), Vector2.Distance(m_startPosition, positionForMinimumDistance));
31 }
32
33
34
35
36 public void Verify()
37 {
38 float minimumDistance = float.MaxValue;
39 Vector2 positionForMinimumDistance = Vector2.zero;
40
41 foreach(var p in m_positionArray)
42 {
43 float d = Vector2.Distance(p, m_startPosition);
44 if (minimumDistance > d)
45 {
46 minimumDistance = d;
47 positionForMinimumDistance = p;
48 }
49 }
50
51 Debug.LogFormat("Minimum distance: {0}, Position: {1}", minimumDistance, positionForMinimumDistance.ToString());
52 }
53}
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2020/07/27 02:42