espace Posted December 31, 2019 Share Posted December 31, 2019 (edited) Hi, I have a specific question based on this case... Assuming i have this objects : pig[0] pig[1] ball if i check the distance on y between ball and the pigs and if i want the biggest value trough the pigs and after do a specific action on the pig who have the biggest value ? i try with array.sort() but i can't find a solution to after identify the concerned pig... Example : ball.y - pig[0].y = 54 ball.y - pig[1].y = 120 ok its pig[1] => do a specific action on it ! Thanks Edited December 31, 2019 by espace Quote Link to comment Share on other sites More sharing options...
Danidre Posted January 2, 2020 Share Posted January 2, 2020 (edited) You only need the id of the pig with the biggest distance, so I'd loop through the pigs and store the id with the biggest y value: let pigIDWithFurthestY; let biggestDistance = 0; for(let i = 0; i < pig.length; i++) { if(ball.y - pig[i].y > biggestDistance) { biggestDistance = ball.y - pig[i].y; pigIDWithFurthestY = i; } } //ok, so at the end pigIDWithFurthestY will contain the i value of the pig that is the furthest in y. //To do an action on it, just call it with // pig[pigIDWithFurthestY] //the variable names are just for you to understand what's happening, but you can name them as you wish. Edited January 2, 2020 by Danidre Fixed the for loop. Quote Link to comment Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.