gpt4 book ai didi

actionscript-3 - 在 Actionscript 3 中查找前 3 个最近的目标

转载 作者:行者123 更新时间:2023-12-04 07:12:05 26 4
gpt4 key购买 nike

我有一个 Points 字符数组,我想获取任何字符并能够遍历该数组并找到前 3 个最近的(使用 Point.distance)邻居。谁能给我一个如何做到这一点的想法?

最佳答案

这是我昨晚发布的代码的新改进版本。它由两个类组成,PointTester 和 TestCase。这一次我也能够测试它!

我们从 TestCase.as 开始

package  {

import flash.geom.Point;
import flash.display.Sprite;

public class TestCase extends Sprite {

public function TestCase() {
// some data to test with
var pointList:Array = new Array();
pointList.push(new Point(0, 0));
pointList.push(new Point(0, 0));
pointList.push(new Point(0, 0));
pointList.push(new Point(1, 2));
pointList.push(new Point(9, 9));

// the point we want to test against
var referencePoint:Point = new Point(10, 10);

var resultPoints:Array = PointTester.findClosest(referencePoint, pointList, 3);

trace("referencePoint is at", referencePoint.x, referencePoint.y);
for each(var result:Object in resultPoints) {
trace("Point is at:", result.point.x, ", ", result.point.y, " that's ", result.distance, " units away");
}
}

}

}

这将是 PointTester.as
package  {

import flash.geom.Point;

public class PointTester {

public static function findClosest(referencePoint:Point, pointList:Array, maxCount:uint = 3):Array{

// this array will hold the results
var resultList:Array = new Array();

// loop over each point in the test data
for each (var testPoint:Point in pointList) {

// we store the distance between the two in a temporary variable
var tempDistance:Number = getDistance(testPoint, referencePoint);

// if the list is shorter than the maximum length we don't need to do any distance checking
// if it's longer we compare the distance to the last point in the list, if it's closer we add it
if (resultList.length <= maxCount || tempDistance < resultList[resultList.length - 1].distance) {

// we store the testing point and it's distance to the reference point in an object
var tmpObject:Object = { distance : tempDistance, point : testPoint };
// and push that onto the array
resultList.push(tmpObject);

// then we sort the array, this way we don't need to compare the distance to any other point than
// the last one in the list
resultList.sortOn("distance", Array.NUMERIC );

// and we make sure the list is kept at at the proper number of entries
while (resultList.length > maxCount) resultList.pop();
}
}

return resultList;
}

public static function getDistance(point1:Point, point2:Point):Number {
var x:Number = point1.x - point2.x;
var y:Number = point1.y - point2.y;
return Math.sqrt(x * x + y * y);
}
}
}

关于actionscript-3 - 在 Actionscript 3 中查找前 3 个最近的目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/158933/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com