Pick nearest value index inside an array

0 favourites
  • 5 posts
From the Asset Store
94 Inside buildings views - Isometric view - PNG transparent - 2048x2048
  • I am currently working on a Megaman X-type game, with multiple weapons, each having its energy gauge;

    When you get an energy pick-up, and your weapon energy is already full, it picks the weapon in the list that has the lower energy quantity and recharge this one instead;

    Until then I used objects by checking which one has its variable the nearest to 0, but I wanted to know if there is a way to do the same by comparing values in an array, and retain the X index of the cell that contains the nearest value to 0?

    Thank you for your time ~

    Tagged:

  • Try Construct 3

    Develop games in your browser. Powerful, performant & highly capable.

    Try Now Construct 3 users don't see these ads
  • Iterate through the array while tracking What index has the lowest value and what that value is.

    IE:

    index: 0 - 1 - 2 - 3

    Value: 4 - 2 - 5 - 1

    0 = 4 - automatically the lowest, its the only other

    1 = 2 if 2 < 4 set 1 lowest - true

    2 = 5 if 5 <2 set 2 lowest - false

    3 = 1 if 1 < 2 set 3 lowest - true

    add value to index 3

    Sidenote:

    if you want to have different requirements for weapons (Different Clip sizes) you should set each value with the % full instead of the number of bullets.

    3 rockets where you can hold 4 = 75% full.

    4 minigun bullets where you can hold 100 = 4% full.

    Choose minigun.

  • It's way more straight forward than that, each weapon have the same amount of max energy, and they recover energy all the same, but that's not the focus here :

    in your example, since index 3 =1, it contains the lowest value of the four indexes here, how would I retain that index from comparing the array values?

    Not sure I understand your example tbh

    EDIT : I think I get how your method works but not sure, I'll have to experiment with it, thanks for the answer ~

  • This is an easy to understand way of doing it.

    1) Create another array were you are going to do some temporary work.

    2) Load your real array into the temporary one using the Load action and the AsJSON expression

    3) Sort the temporary array using the Sort action. This sorts the values in ascending order.

    4) Now the first element of the temporary array is the one closest to 0, so search for the first element of the temporary array in the real array using the IndexOf action.

    That should get you the index of the lowest value in the real array.

  • Thanks for that method, but I found how to adapt winstreak logic for the engine needs;

    Thank you both for helping!

Jump to:
Active Users
There are 1 visitors browsing this topic (0 users and 1 guests)