-1

I have a script in which I want to find the chunk my player is in. Simplified version:

float x = -5
float y = -15
int chunkSize = 16

int player_chunk_x = int(x / chunkSize)
int player_chunk_y = int(y / chunkSize)

This gives the chunk the player is in, but when x or y is negative but not less than the chunkSize (-16), player_chunk_x or player_chunk_y is still 0 or '-0' when I need -1

Of course I can just do this:

if (x < 0) x--
if (y < 0) y--

But I was wondering if there is a better solution to my problem.

Thanks in advance.

Gerhardh
  • 11,688
  • 4
  • 17
  • 39

4 Answers4

4

Since C++20 it's impossible to get an integral type signed negative zero, and was only possible in a rare (but by no means extinct) situation where your platform had 1's complement int. It's still possible in C (although rare), and adding 0 to the result will remove it.

It's possible though to have a floating point signed negative zero. For that, adding 0.0 will remove it.

Note that for an integral -0, subtracting 1 will yield -1.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483
3

Your issue is that you are casting a floating point value to an integer value.

This rounds to zero by default.

If you want consistent round down, you first have to floor your value:

int player_chunk_x = int(std::floor(x / chunkSize);
Guillaume Gris
  • 2,135
  • 17
  • 34
1

If you don't like negative numbers then don't use them:

int player_chunk_x = (x - min_x) / chunkSize;
int player_chunk_y = (y - min_y) / chunkSize;
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
1

If you want integer, in this case -1 on ( -5%16 or anything like it ) then this is possible using a math function:

Possible Ways :

  1. using floor ->
float x = -5;
float y = -15;
int chunkSize = 16;

int player_chunk_x = floor(x / chunkSize) 
// will give -1 for (-5 % 16);
// 0 for (5%16) 
// 1 for any value between 1 & 2 and so on 

int player_chunk_y = floor(y / chunkSize);
ADITYA AHLAWAT
  • 140
  • 1
  • 13