JavaScript:函数返回最接近的值

时间:2019-02-16 12:40:48

标签: javascript

我试图将最接近的对象的值返回到我在函数中的位置。

我试图将实体放置在数组中,然后尝试通过for循环将最近的对象返回到我的位置,但是没有用。我该怎么办?

function getMyEntity() {
  return Game.currentGame.world.localPlayer.entity.getFromTick();
}

function getOtherEntity() {
  var MyPlayerEntity = getMyEntity();

  var entities = Game.currentGame.world.entities;
  for (var uid in entities) {
    // how i get closest entity to my player entity here?
    var gameObject = entities[uid].fromTick;

    console.log(entities[uid].fromTick.position, MyPlayerEntity.position)
    if (gameObject.entityClass == "Prop" && gameObject.uid !== MyPlayerEntity.uid) {
      return gameObject;
    }
  }
}

function aimAssist() {
  var MyPlayerEntity = getMyEntity();
  var OtherEntity = getOtherEntity();
  if (OtherEntity == undefined) return

  var aimPosition = {
    x: OtherEntity.position.x - MyPlayerEntity.position.x,
    y: OtherEntity.position.y - MyPlayerEntity.position.y
  }
  return aimPosition;
}

3 个答案:

答案 0 :(得分:1)

我会给你一个不好的建议,因为它会随着O(n ^ 2)的复杂性而发展,但随着游戏的发展,它会变得很糟糕。阅读有关四叉树的知识,看看是否可以这样做。同时可以比较欧几里得距离,不需要取平方根:

Object.keys(entities)
.map(function(d,i){
  var dx = entities[d].fromTick.position.x - MyPlayerEntity.position.x, 
       dy = entities[d].fromTick.position.y - MyPlayerEntity.position.y,
       result = {D:(dx * dx) + (dy + dy), obj:entities[d] , valueOf: function(){return this.D};
  return result;
}).sort(function(a,b){
    return a-b;
})[0].obj; //this returns the closest one

所以您的原始功能是这样的:

function getOtherEntity() {
  var MyPlayerEntity = getMyEntity();

  var entities = Game.currentGame.world.entities;
  return Object.keys(entities)
    .map(function(d,i){
      var dx = entities[d].fromTick.position.x - MyPlayerEntity.position.x, 
           dy = entities[d].fromTick.position.y - MyPlayerEntity.position.y,
           result = {D:(dx * dx) + (dy + dy), obj:entities[d] , valueOf: function(){return this.D};
      return result;
    }).sort(function(a,b){
        return a-b;
    })[0].obj; //this returns the closest one
}

答案 1 :(得分:0)

我将创建一个包含对象ID和距离的对象数组,并按距离对它进行排序。 第一个数组项目最接近播放器。

数组可能看起来像 [{uid: 1234, distance: 12}, {uid: 1235, distance: 16}, ...]

您可以使用arrayName.sort(sortingFunction)

对数组进行排序

答案 2 :(得分:0)

假设您可以从gameObject.positionMyPlayerEntity.position获得x和y坐标,则可以使用一些Pitagoras:c ^ 2 = a ^ 2 + b ^ 2,其中c为距离

let a = gameObject.position.x - MyPlayerEntity.position.x;
let b = gameObject.position.y - MyPlayerEntity.position.y;
let distanceSquared = a*a + b*b;

由于您似乎不需要确切的距离并且sqrt()很昂贵,因此可以使用distanceSquared中的值和在循环外部声明的其他变量来跟踪

let closestDistance;
let closest;

进行正确的比较

if(distanceSquared < closestDistance){
    closestDistance = distanceSquared;
    closest = gameObject;
}

遍历数组后,最接近的实体引用应为:

return closest;