Minecraft Java Edition – How to Find the Absolute Value of a Score

minecraft-commandsminecraft-java-edition

So I want to find the absolute value of two coordinates in Minecraft 1.16.3 to see how far apart they are. So I make the cords into scoreboard values so I could use operations. Could I use the pipes or '|' like in math. How would I do it without a bunch of other commands to test if the values are below 0 or something. If any data packs are needed that's fine. I just wanted to know if I could do it like in normal math e.g. |1-10| that equals 9. Thanks for helping!

Best Answer

Hover your mouse over links for additional information.

I found what I think is a very simple way. The only math operations available with the scoreboard are +=, -=, *=, /=, and %= (modulo, like in coding).
The setup is complex, but the math used is simple and elegant. Bear with me.

Here are the scoreboard objectives I'll be using:

  • const: A constant values scoreboard.
  • vals: A scoreboard objective where you input all the values. With the press of a button, all the values in this scoreboard are replaced with their respective absolute values.
    Important notice: If there are other scoreboard machines in your world, you can't use fake players for this. You'll need to use armour stands to store your scoreboard values.
    Sorry, that's what makes this setup complex. If I find a better way, it'll be up here before you can say Jack Robinson.

First, run this command:

/scoreboard players set -1 const -1

The command in the command block is:

/execute as @e[scores={vals=..2147483647}] if score @s vals matches ..-1 run scoreboard players operation @s vals *= -1 const

If any of the scores on vals is −1 or below, multiply them by −1.