1

I have some objects in array with coordinates.

var players = [
{x:100, y:100, pid:1},
{x:-100, y:200, pid:2},
{x:600, y:1200, pid:3}
]

var mousepos = {x:50, y:0} var selected = null

And I want to calculate which of these objects have closest coordinates to mousepos to select it pid selected = pid of closest coords to mousepos

if anyone could give me easy done code?

Divyanshu Rawat
  • 4,421
  • 2
  • 37
  • 53
Zimek
  • 11
  • 2

3 Answers3

0

Mate here is the answer. Use the distance formula to calculate the distance between points. One with the smallest distance is the closest point.

Fomula :- Sqrt((x2-x1)2 + (y2-y1)2)

0

It seems you are trying to calculate Euclidean Distance. If so then you can use Math build in object. Once the distance is calculated then you can return the index. Using this index retrieve the he object from the players

var players = [{
    x: 100,
    y: 100,
    pid: 1
  },
  {
    x: -100,
    y: 200,
    pid: 2
  },
  {
    x: 600,
    y: 1200,
    pid: 3
  }
]
var mousepos = {
  x: 50,
  y: 0
}

function calculateEuclidean() {
  let selectedPid = 0;
  players.forEach(function(item, index) {
    let distance = Math.sqrt(Math.pow((item.x - mousepos.x), 2) + Math.pow((item.y - mousepos.y), 2))
    if (index === 0) {
      selectedPid = index
    } else if (distance < selectedPid) {
      selectedPid = index;
    }
  })
  return players[selectedPid];
}


console.log(calculateEuclidean())
brk
  • 48,835
  • 10
  • 56
  • 78
0

Working example given by random from discord

    let closestPlayer = undefined;
    let closestDist = undefined;
    for (let i = 0; i < players.length; i++) {
      let player = players[i];
      let distance = Math.hypot(player.x - mousepos.x, player.y - mousepos.y);
      if (closestPlayer == undefined || distance <= closestDist) {
        closestPlayer = player;
        closestDist = distance;
      }
    }
      console.log(closestPlayer)
Zimek
  • 11
  • 2