Godot Version
Godot version 4.4
Question
Hello
Chunk is 8, 8
I need: tile (-1, -1) → chunk (-1, -1) and tile (8, 8) → chunk (1, 1) etc
But this function doesn’t work well:

On video at console, I get coord chunk and coord tile:
coord chunk : (0, 0) coord tile : (-1, -1), but coord chunk : (-1, -1) coord tile : (-8, -8)
Maybe:
func get_chunk(pos: Vector2) -> Vector2i:
var tilecoord = local_to_map(pos)
var x = int(tilecoord.x) >> 3
var y = int(tilecoord.y) >> 3
return Vector2i(x, y)
The right shift by three is equivalent to dividing by eight, but ought to give you correct results.
But, if chunk size is 16, 16?
My code assumes a power of two size.
1 << 1 == 2 # b00000001 -> b00000010
1 << 2 == 4 # b00000001 -> b00000100
1 << 3 == 8 # b00000001 -> b00001000
1 << 4 == 16 # b00000001 -> b00010000
1 << 5 == 32 # b00000001 -> b00100000
[...]
32 >> 5 == 1 # b00100000 -> b00000001
16 >> 4 == 1 # b00010000 -> b00000001
8 >> 3 == 1 # b00001000 -> b00000001
4 >> 2 == 1 # b00000100 -> b00000001
2 >> 1 == 1 # b00000010 -> b00000001
Right shift <<
and left shift >>
shift bits in the value, which is equivalent to multiplying and dividing by powers of two, and it’s way faster than integer multiplication and division.
1 Like