我想检查无人机[i]。位置是否在每个无人机[除了我]的安全区域内。 基本上我不想检查无人机[i]。位是否在无人机[i] .safe_area内。
也许我需要另一个for循环或什么?
我看到了像
一样的东西if(i== ) continue;
但是我该怎么做?
代码:
For each Drone I have:
string ip (example "192.168.1.10"
Point position (x,y)
Point Safe_area
for(int i = 0 ; i<drone.length;i++)
{
//i think I need to check drone's IP to know the current drone being iterated
If(drone[i].position //is inside every drone[EXCEPT i]’s safe area
{
//debug: Which drone’s safe area is drone[i].position inside?
}
}
答案 0 :(得分:0)
你可以使用linq。
public class Drone
{
public int ID { get; set; }
public Point Position { get; set; }
public bool IsInsideSafearea(Point point)
{
throw new NotImplementedException();
}
}
public class Class1
{
public void DoSomething()
{
var drones = new Drone[]
{
new Drone() {ID = 0, Position = new Point(1, 2) },
new Drone() {ID = 1, Position = new Point(3, 4) },
new Drone() {ID = 2, Position = new Point(4, 2) },
};
var myDrone = drones[0];
bool result = drones
.Where(d => d.ID != myDrone.ID)
.All(d => d.IsInsideSafearea(myDrone.Position));
}
}
答案 1 :(得分:0)
根据我对你的问题的理解,你基本上有一架无人机,无人机有一个安全的区域。现在你想检查一架无人机是否在另一架无人机的安全区域内。
___________
/ \
/ \
/ --------`
| /
| Drone Y's Safe Area /___
| `
--------------------------`
换句话说,您正在寻找另一架无人机的位置是否在Drone Y的安全区域内。所以你需要找到一个点是否在多边形内。您可以创建一个类:
public class Drone {
public Point Position { get; set; }
public Point[] SafeArea { get; set; }
public bool CheckIfDroneWithinMySafeArea(Drone drone) {
return IsWithinPolygon( this.SafeArea, drone.Position );
}
public static bool IsWithinPolygon(Point[] poly, Point dronePosition) {
bool isWithinPolygon = false;
if( poly.Length < 3 ) {
return isWithinPolygon;
}
var oldPoint = new
Point( poly[ poly.Length - 1 ].X, poly[ poly.Length - 1 ].Y );
Point p1, p2;
for( int i = 0; i < poly.Length; i++ ) {
var newPoint = new Point( poly[ i ].X, poly[ i ].Y );
if( newPoint.X > oldPoint.X ) {
p1 = oldPoint;
p2 = newPoint;
}
else {
p1 = newPoint;
p2 = oldPoint;
}
if( ( newPoint.X < dronePosition.X ) == ( dronePosition.X <= oldPoint.X )
&& ( dronePosition.Y - ( long ) p1.Y ) * ( p2.X - p1.X )
< ( p2.Y - ( long ) p1.Y ) * ( dronePosition.X - p1.X ) ) {
isWithinPolygon = !isWithinPolygon;
}
oldPoint = newPoint;
}
return isWithinPolygon;
}
}
以下是用法:
var d1 = new Drone();
// set d1's position and safe area
var drones = new List<Drone>();
// Add drones to above list
// Now check if any of the drones are within d1's safe area
var dronesWithinD1zSafeArea = drones.Where( x => d1.CheckIfDroneWithinMySafeArea( x ) ).ToList();
请记住,我并不担心封装,所以你需要注意这一点,不要让SafeArea
在施工后被操纵,但这取决于你的需要。
我从here获得了检查多边形内部的代码。
修改强>
在你对这个答案的评论中提到:
安全区域是一个简单的方块。
以上代码适用于任何形状(三角形,矩形)。但是对于rectagle,你可以使用这个更短的代码:
public class Drone {
public System.Windows.Point Position { get; set; }
public Rectangle SafeArea { get; set; }
public bool CheckIfDroneWithinMySafeArea(Drone drone) {
return this.SafeArea.Contains( drone.Position );
}
}