Javascript数组排序和拼接
我正在做一个游戏,我需要精灵找到最近的“食物”并朝他们走去。我很难找到正确的代码来实现这一点。他们似乎第一次吃到的食物都很好,但是当有多种食物时,雪碧在每种食物之间都会犹豫不决,而且吃不下任何一种。仍然没有太多深入的数组经验需要理解 我正在使用cocos2d框架Javascript数组排序和拼接,javascript,arrays,sorting,cocos2d-iphone,box2d,Javascript,Arrays,Sorting,Cocos2d Iphone,Box2d,我正在做一个游戏,我需要精灵找到最近的“食物”并朝他们走去。我很难找到正确的代码来实现这一点。他们似乎第一次吃到的食物都很好,但是当有多种食物时,雪碧在每种食物之间都会犹豫不决,而且吃不下任何一种。仍然没有太多深入的数组经验需要理解 我正在使用cocos2d框架 update:function (dt) { for (var i = 0; i < this._gubz.length; i++) { var gub = this._gubz[i];
update:function (dt) {
for (var i = 0; i < this._gubz.length; i++)
{
var gub = this._gubz[i];
if (this._food.length>0)
{
var distances = new Array();
for (var w = 0; w < this._food.length; w++)
{
var food = this._food[w];
var location = food.getPosition();
var distance = cc.pDistance(location,gub.getPosition());
}
var smallestDistance = Math.min.apply(Math,distances);
var indexOfNumber = distances.indexOf(smallestDistance);
var closestFood = this._food[indexOfNumber];
gub.currentTarget = indexOfNumber;
}
}
for (var i = 0; i < this.foodToRemove.length; i++)
{
this.removeChild(this.foodToRemove[i].GetUserData());
this._food.splice(this._food.indexOf(this.foodToRemove[i].GetUserData()),1)
this.world.DestroyBody(this.foodToRemove[i]);
}
}
更新:功能(dt){
对于(var i=0;i0)
{
var距离=新数组();
对于(var w=0;w
如果要对javascript数组应用排序,请使用sort变量
this._food = this._food.sort(function(a, b) {
return a.smallestDistance > b.smallestDistance ? -1 : a.smallestDistance < b.smallesDistance ? 1 : 0;
});
你应该开始了
嗯
this._food = this._food.filter(function(element) {
return elementDoesNotExist(element);
});