-8

I am trying to make a raycaster game in Javascript, and to do so, I am following this tutorial, which is written in C++.

My problem stems from trying to convert the following two lines to javascript:

int tx = (int)(texWidth * (floorX - cellX)) & (texWidth - 1);
color = (color >> 1) & 8355711; // make a bit darker

I don't know what the "&" and ">>" mean in those two lines. Is there an equivalent in Javascript?

digito_evo
  • 3,216
  • 2
  • 14
  • 42
mbg206
  • 21
  • 5
  • 2
    The equivalents are [`&`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_AND) and [`>>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Right_shift). These can be found in any list of JS operators. – Dave Newton Dec 05 '21 at 22:43
  • 1
    Those are [bitwise operators](https://www.w3schools.com/js/js_bitwise.asp), they are the same in most modern languages. – Olian04 Dec 05 '21 at 22:44
  • These are bitwise operators, `color >> 1` will halve the `color`'s value. `&` is the bitwise **AND**. Also, **8355711** is called a bitmask. – digito_evo Dec 05 '21 at 22:48
  • 2
    When in doubt about operators, search for “[language here] operators”.. – user2864740 Dec 05 '21 at 22:54
  • 1
    Tangentially related: bitmasks are generally represented as hex so they make more sense: `0x7F7F7F`. This bitmask has the effect of dropping the high bit of an RGB triple. – Dave Newton Dec 05 '21 at 22:55
  • 2
    That code is so nasty. The hard-coded value 8355711 is much better represented in hex: 0x7f7f7f where you can actually _see_ what it does. It is dropping the most significant bit of each color channel. So if you see it in terms of that, you can see that you have shifted all bits one place to the right and so the bitmask will then remove the overflow bit from the adjacent color channel. Effectively, this operation divides each color channel by 2. So "a bit" darker means "considerably" darker (depending on your color space). There should be a code comment explaining this. – paddy Dec 05 '21 at 22:55
  • You probably want [`>>>`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Unsigned_right_shift) in JavaScript to get something similar to C++'s `>>`. – Ted Lyngmo Dec 05 '21 at 22:59

2 Answers2

1

>> is the right bit-shift operator and & is the bitwise-and operator, both of them are available in JavaScript

Salvage
  • 448
  • 1
  • 4
  • 13
1

The code directly translates to JS with the removal of the (int) typecast and the replacement of int with let/var/const.

let tx = (texWidth * (floorX - cellX)) & (texWidth - 1);    
color = (color >> 1) & 8355711; // make a bit darker 

& is the bitwise and, >> is the bitshift right, explained well here.

Juicestus
  • 442
  • 1
  • 7
  • 14