官术网_书友最值得收藏!

The MoveShip function

We are going to need to jump back into the WebAssembly C module. The webgl.c file is a copied version of canvas.c where the only changes we need to make are inside of the MoveShip function. Here is the new version of MoveShip:

void MoveShip() {
ship_x += 0.002;
ship_y += 0.001;

if( ship_x >= 1.16 ) {
ship_x = -1.16;
}

if( ship_y >= 1.21 ) {
ship_y = -1.21;
}

EM_ASM( ShipPosition($0, $1), ship_x, ship_y );
}

The changes are all conversions from pixel space into WebGL clip space. In the 2D canvas version, we were adding two pixels to the ship's x coordinate and one pixel to the ship's y coordinate every frame. But in WebGL, moving the x coordinate by two would be moving it by the entire width of the screen. So, instead, we have to modify these values into small units that would work with the WebGL coordinate system:

ship_x += 0.002;
ship_y += 0.001;

Adding 0.002 to the x coordinate moves the ship by 1/500th of the width of the canvas each frame. Moving the y coordinate by 0.001 moves the ship on the y-axis by 1/1,000th of the height of the screen each frame. You may notice that in the 2D canvas version of this app, the ship was moving to the right and down. That was because increasing the y coordinate in the 2D canvas coordinate system moves an image down the screen. In the WebGL coordinate system, the ship moves up. The only other thing we have to do is change the coordinates at which the ship wrapped its x and y coordinates to WebGL clip space:

if( ship_x >= 1.16 ) {
ship_x = -1.16;
}

if( ship_y >= 1.21 ) {
ship_y = -1.21;
}

Now that we have all of our source code, go ahead and run emcc to compile our new webgl.html file:

emcc webgl.c -o webgl.html --shell-file webgl_shell.html

Once you have webgl.html compiled, load it into a web browser. It should look like this:

Figure 3.1: Screenshot of our WebGL app

It is important to remember that the app must be run from a web server, or using emrun. If you do not run the app from a web server, or use emrun, you will receive a variety of errors when the JavaScript glue code attempts to download the WASM and data files. You should also know that IIS requires additional configuration in order to set the proper MIME types for the .wasm and .data file extensions.

Now that we have all of this working in WebGL, in the next chapter, I will talk about how much easier all of this would have been if we just did it using SDL in the first place.

主站蜘蛛池模板: 新巴尔虎左旗| 江油市| 雅江县| 文成县| 临桂县| 贵德县| 河北区| 荣昌县| 阿克苏市| 南汇区| 福安市| 忻城县| 乃东县| 视频| 安泽县| 葫芦岛市| 麻阳| 琼中| 阜康市| 通渭县| 札达县| 罗平县| 尼木县| 平山县| 呈贡县| 麻城市| 原平市| 左贡县| 东乡县| 阳泉市| 仁怀市| 宁陕县| 沾化县| 贵德县| 海宁市| 思南县| 肥西县| 隆子县| 阿拉善左旗| 巩留县| 三门县|