Rounding Vector Look Vector XYZ values to either -1, 0, or 1

For my own personal game development, I made a math algorithm that rounds vector lookvector XYZ values to either -1, 0, or 1… (Open / Close Door Logic)

Here is my current code:

(ignore the Y value because it’s going to be an ignored variable)


Let’s pretend you have the lookvector {0.2, Y, 0.6}

I want to round it to {0, Y, 1}

Is there any other method (besides my own) that is more optimized for rounding look vector XYZ values to either -1, 0, or 1?

Thanks for reading this.

I might be misreading your post, but if you want to round to the nearest of those three numbers you can just use math.floor and clamp the value from that.

math.clamp(math.floor(x + 0.5), -1, 1)

This will round to the nearest number, and if it’s above 1 will round down to 1, while if it’s below -1 it will round up to -1. The 0.5 is because math.floor always rounds down, and to make 0.5-0.99999 round up you can just add 0.5 to make that range 1-1.499999 (which will go down to 1).

Edit: added an extra parenthesis by accident

2 Likes

If I’m not mistaken, math.sign(x)*math.ciel(math.abs(x)) for each component should do it. That’ll round the result to 1 or 0 depending upon what it is, and then multiply it by the sign of the original number (which will be -1, 0, or -1).

4 Likes

So as far as I know, look vector XYZ component values are between -1 and 1… I will look into both of your guys’ methods today.

Thanks for the optimized solution.

His solution is great and more readable, so if you want readability then you should definitely use his method. If both of ours work the same for your purposes, mine seems to be slightly more efficient. After running both of our methods, I got 1,000,000 repeats of his taking 1.036175 seconds while mine took 0.883054 seconds.

1 Like

Well, lets pretend that the Vector is {0.3, Y, Z}.

With your method, would it round to {0, Y, Z}?

(this is a more abstract example)

Mine wouldn’t, no. Posatta’s would though. I may have forgotten to properly round it. With that in mind I would go with Posatta’s solution.

1 Like

Alright, thanks again though for trying (and putting up with me lol)

If you were curious about what I am using this algorithm for, it’s made for opening / closing building doors…

I compare the player’s lookvector to the door’s lookvector, and I decide on which direction the door should open (if the door is already closed).