From 980fe00a74a9ad013b945755415ace2e5429c3c2 Mon Sep 17 00:00:00 2001 From: Alexey Pyltsyn Date: Wed, 27 Oct 2021 02:31:24 +0300 Subject: [RU] Remove notranslate (#2874) --- files/ru/games/anatomy/index.html | 16 +++++----- .../index.html | 36 +++++++++++----------- .../2d_breakout_game_phaser/extra_lives/index.html | 14 ++++----- 3 files changed, 33 insertions(+), 33 deletions(-) (limited to 'files/ru/games') diff --git a/files/ru/games/anatomy/index.html b/files/ru/games/anatomy/index.html index b3022fa527..019b6276ab 100644 --- a/files/ru/games/anatomy/index.html +++ b/files/ru/games/anatomy/index.html @@ -32,7 +32,7 @@ original_slug: Games/Анатомия

Некоторый код должен выполняться кадр за кадром, так зачем же прикреплять эту функцию к чему-то другому, кроме графика перерисовки браузера? В Web, {{ domxref("window.requestAnimationFrame()") }} будет основой большинства хорошо запрограммированных покадровых основных циклов.  Callback функция должна быть передана ему при вызове. Callback функция будет выполнена в подходящее время перед следующей перерисовкой. Вот пример простого основного цикла:

-
window.main = function () {
+
window.main = function () {
   window.requestAnimationFrame( main );
 
   // Код, который цикл должен выполнить
@@ -56,7 +56,7 @@ main(); // Start the cycle

У нашего цикла есть две очевидные проблемы: main() загрязняет {{ domxref("window") }} объект (в нем хранятся все глобальные переменные) и код не оставляет нам возможность остановить цикл, если только вся вкладка не будет закрыта или обновлена. Для решения первой проблемы, если нужно, чтобы основной цикл просто выполнялся и вам не нужен лёгкий (прямой) доступ к нему, вы можете поместить его внутрь самовызывающейся Function Expression (IIFE).

-
/*
+
/*
 * Начинаем с точки с запятой в случае, если какая-либо строка кода выше данного примера
 * полагается на автоматическую вставку точки с запятой (ASI). Браузер может случайно решить,
 * что весь этот код начинается с предыдущей строки. Первая точка с запятой отмечает начало
@@ -81,7 +81,7 @@ main(); // Start the cycle

Чтобы остановить основной цикл, вам понадобиться отменить вызов main() с помощью {{ domxref("window.cancelAnimationFrame()") }}. Необходимо передать в cancelAnimationFrame() идентификатор последнего вызова requestAnimationFrame(). Давайте предположим, что функции и переменные вашей игры были определены в пространстве имён, которое вы назвали MyGame.  В таком случае, основной цикл будет выглядеть следующим образом:

-
/*
+
/*
 * Начинаем с точки с запятой в случае, если какая-либо строка кода выше данного примера
 * полагается на автоматическую вставку точки с запятой (ASI). Браузер может случайно решить,
 * что весь этот код начинается с предыдущей строки. Первая точка с запятой отмечает начало
@@ -102,7 +102,7 @@ main(); // Start the cycle

Теперь у нас есть переменная stopMain, объявленная в нашем пространстве имён MyGame, которая содержит идентификатор последнего вызова requestAnimationFrame() нашего основного цикла.  В любой момент мы может остановить основной цикл, сказав браузеру, чтобы тот отменил запрос, соответствующий последнему маркеру.

-
window.cancelAnimationFrame( MyGame.stopMain );
+
window.cancelAnimationFrame( MyGame.stopMain );

Ключ к программированию основного цикла в JavaScript заключается в том, чтобы прикрепить его к любому событию, которое должно управлять вашими действиями, и обращать внимание на то, как различные системы участвуют во взаимодействии. У вас может быть несколько компонентов, управляемых несколькими различными типами событий. Это может показаться излишним усложнением, но также может быть просто хорошей оптимизацией (не обязательно, конечно). Проблема в том, что вы не выстраиваете типичный основной цикл. В JavaScript вы используйте основной цикл браузера и стараетесь сделать это эффективно. 

@@ -131,12 +131,12 @@ main(); // Start the cycle

Это значение нельзя использовать само по себе, потому что оно относиться к неинтересному событию, но его можно вычесть из другой временной ветки, чтобы чётко и точно определить, сколько времени прошло между этими двумя точками. Чтобы получить одну из этих временных меток, вы можете вызвать window.performance.now() и сохранить результат в переменную. 

-
var tNow = window.performance.now();
+
var tNow = window.performance.now();
 

Возвращаемся к основному циклу. Часто вам понадобиться узнать, когда ваша основная функция  была вызвана. Это обычное дело, window.requestAnimationFrame() при выполнении всегда предоставляет метку DOMHighResTimeStamp в качестве аргумента для колбэк-функций. Это приводит к очередному улучшению нашего основного цикла. 

-
/*
+
/*
 * Начинаем с точки с запятой в случае, если какая-либо строка кода выше данного примера
 * полагается на автоматическую вставку точки с запятой (ASI). Браузер может случайно решить,
 * что весь этот код начинается с предыдущей строки. Первая точка с запятой отмечает начало
@@ -172,7 +172,7 @@ main(); // Start the cycle

If your game can hit the maximum refresh rate of any hardware you support then your job is fairly easy. You can simply update, render, and then do nothing until VSync.

-
/*
+
/*
 * Starting with the semicolon is in case whatever line of code above this example
 * relied on automatic semicolon insertion (ASI). The browser could accidentally
 * think this whole example continues from the previous line. The leading semicolon
@@ -244,7 +244,7 @@ main(); // Start the cycle

Note: This example, specifically, is in need of technical review.

-
/*
+
/*
 * Starting with the semicolon is in case whatever line of code above this example
 * relied on automatic semicolon insertion (ASI). The browser could accidentally
 * think this whole example continues from the previous line. The leading semicolon
diff --git a/files/ru/games/techniques/3d_on_the_web/building_up_a_basic_demo_with_three.js/index.html b/files/ru/games/techniques/3d_on_the_web/building_up_a_basic_demo_with_three.js/index.html
index 8c89ecc871..da8c8b434c 100644
--- a/files/ru/games/techniques/3d_on_the_web/building_up_a_basic_demo_with_three.js/index.html
+++ b/files/ru/games/techniques/3d_on_the_web/building_up_a_basic_demo_with_three.js/index.html
@@ -31,7 +31,7 @@ translation_of: Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_Thr
 
 

Здесь находится HTML структура, которую мы будем использовать:

-
<!DOCTYPE html>
+
<!DOCTYPE html>
 <html>
 <head>
 	<meta charset="utf-8">
@@ -60,7 +60,7 @@ translation_of: Games/Techniques/3D_on_the_web/Building_up_a_basic_demo_with_Thr
 
 

Renderer это инструмент для отрисовки сцены в браузере. Есть 2 вида таких инструментов: WebGL по умолчанию, другие - Canvas, SVG, CSS, и DOM. Они различаются по тому как все рендерится. Несмотря на различия в них, для пользователя все будет выглядеть одинаково. Поэтому, вы можете выбрать запасной вариант на случай, если браузер пользователя не поддерживает выбранную вами технологию.

-
var renderer = new THREE.WebGLRenderer({antialias:true});
+
var renderer = new THREE.WebGLRenderer({antialias:true});
 renderer.setSize(WIDTH, HEIGHT);
 renderer.setClearColor(0xDDDDDD, 1);
 document.body.appendChild(renderer.domElement);
@@ -74,7 +74,7 @@ document.body.appendChild(renderer.domElement);
 
 

Сцена (scene) это место, где все происходит. Когда создаются новые объекты, они добавляются в сцену, чтобы их можно было увидеть. В three.js роль сцены выполняет объект Scene. Давайте создадим его, добавив следующих код:

-
var scene = new THREE.Scene();
+
var scene = new THREE.Scene();
 

Позже, мы будем использовать метод .add() для добавления объектов в сцену.

@@ -83,7 +83,7 @@ document.body.appendChild(renderer.domElement);

У нас есть сцена, теперь необходимо создать камеру. С помощью следующих строк мы добавим камеру, установим её позицию в координатной системе и направим её на нужную нам точку, где расположено то, что мы хотим видеть:

-
var camera = new THREE.PerspectiveCamera(70, WIDTH/HEIGHT);
+
var camera = new THREE.PerspectiveCamera(70, WIDTH/HEIGHT);
 camera.position.z = 50;
 scene.add(camera);
 
@@ -108,7 +108,7 @@ scene.add(camera);

Всё уже готово, но мы пока что ничего не видим. Хотя мы настроили рендерер, нам всё равно нужно запустить рендеринг. Функция render() выполнит эту работу с небольшой помощью requestAnimationFrame(), которая заставляет сцену постоянно перерисовываться в каждом кадре:

-
function render() {
+
function render() {
 	requestAnimationFrame(render);
 	renderer.render(scene, camera);
 }
@@ -123,7 +123,7 @@ render();
 
 

Now our scene is properly rendering, we can start adding 3D shapes. To speed up development, Three.js provides a bunch of predefined primitives, which you can use to create shapes instantly in a single line of code. There's cubes, spheres, cylinders, and more complicated shapes available. Detail like drawing required vertices and faces, for a given shape, is handled by the Three framework, so we can focus on higher level coding. Let's start, by defining the geometry for a cube shape, adding the following just above the render() function:

-
var boxGeometry = new THREE.BoxGeometry(10, 10, 10);
+
var boxGeometry = new THREE.BoxGeometry(10, 10, 10);
 

In this case, we define a simple cube that is 10 x 10 x 10 units. The geometry itself is not enough though, we also need a material that will be used for our shape.

@@ -132,7 +132,7 @@ render();

A material is what covers an object, the colors, or textures on its surface. In our case, we will choose a simple blue color to paint our box. There are a number of predefined materials which can be used: Basic, Phong, Lambert. Let's play with the last two later, but for now, the Basic one should be enough:

-
var basicMaterial = new THREE.MeshBasicMaterial({color: 0x0095DD});
+
var basicMaterial = new THREE.MeshBasicMaterial({color: 0x0095DD});
 

Add this line below the previously added.

@@ -143,7 +143,7 @@ render();

To apply the material to a geometry, a mesh is used. This takes on a shape, and adds the specified material to every face:

-
var cube = new THREE.Mesh(boxGeometry, basicMaterial);
+
var cube = new THREE.Mesh(boxGeometry, basicMaterial);
 

Again, add this line below the one you previously added.

@@ -152,12 +152,12 @@ render();

Сейчас мы создали куб, используя 'geometry' и 'material'. Последнее, что мы должны сделать - добавить куб на сцену. Добавьте в код эту строку:

-
scene.add(cube);
+
scene.add(cube);
 

Если вы сохраните код и обновите вкладку браузера, вы увидите квадрат, а не куб, потому, что он стоит ровно напротив камеры и мы видим только одну сторону. У объектов есть полезное свойство - мы можем изменять их как хотим. Например, вы можете вращать его и масштабировать, сколько угодно. Что давайте немного повернём его, чтобы видеть больше сторон.  Добавить в конец кода эту строку:

-
cube.rotation.set(0.4, 0.2, 0);
+
cube.rotation.set(0.4, 0.2, 0);
 

Поздравляю, вы создали объект в 3D-среде! This might have proven easier than you first thought? Here's how it should look:

@@ -174,12 +174,12 @@ render();

Now we will add more shapes to the scene, and explore other shapes, materials, lighting, and more. Let's move the cube to the left, to make space for some friends. Adding the following line just below the previous one:

-
cube.position.x = -25;
+
cube.position.x = -25;
 

Now onto more shapes and materials. What might you input to add a torus, wrapped in the Phong material? Try adding the following lines, just below the lines defining the cube.

-
var torusGeometry = new THREE.TorusGeometry(7, 1, 6, 12);
+
var torusGeometry = new THREE.TorusGeometry(7, 1, 6, 12);
 var phongMaterial = new THREE.MeshPhongMaterial({color: 0xFF9500});
 var torus = new THREE.Mesh(torusGeometry, phongMaterial);
 scene.add(torus);
@@ -189,7 +189,7 @@ scene.add(torus);
 
 

We can choose more fun predefined shapes. Let's play some more. Add the following lines, below those defining the torus:

-
var dodecahedronGeometry = new THREE.DodecahedronGeometry(7);
+
var dodecahedronGeometry = new THREE.DodecahedronGeometry(7);
 var lambertMaterial = new THREE.MeshLambertMaterial({color: 0xEAEFF2});
 var dodecahedron = new THREE.Mesh(dodecahedronGeometry, lambertMaterial);
 dodecahedron.position.x = 25;
@@ -204,7 +204,7 @@ scene.add(dodecahedron);
 
 

There are various types of light sources available in Three.js. The most basic is PointLight, which works like a flashlight, shining a spotlight in a defined direction. Add the following lines, below your shape definitions:

-
var light = new THREE.PointLight(0xFFFFFF);
+
var light = new THREE.PointLight(0xFFFFFF);
 light.position.set(-10, 15, 50);
 scene.add(light);
 
@@ -223,7 +223,7 @@ scene.add(light);

Вращать фигуры просто. Вы просто добавляете или отнимаете значение по оси вращения. Добавьте эту строку кода сразу после: requestAnimationFrame() invocation inside the render function:

-
cube.rotation.y += 0.01;
+
cube.rotation.y += 0.01;
 

This rotates the cube on every frame, by a tiny bit, so the animation looks smooth.

@@ -232,12 +232,12 @@ scene.add(light);

We can also scale an object. Applying a constant value, we would make it grow, or shrink just once. Let's make things more interesting. First, we implement a helper variable, called t, for counting elapsed time. Add it right before the render() function:

-
var t = 0;
+
var t = 0;
 

Now let's increase the value by a given constant value, on each frame of the animation. Add the following lines, just below the requestAnimationFrame() invocation:

-
t += 0.01;
+
t += 0.01;
 torus.scale.y = Math.abs(Math.sin(t));
 
@@ -249,7 +249,7 @@ torus.scale.y = Math.abs(Math.sin(t));

Aside from rotation, and scaling, we can additionally move objects around the scene. Add the following, again just below our requestAnimationFrame() invocation:

-
dodecahedron.position.y = -7*Math.sin(t*2);
+
dodecahedron.position.y = -7*Math.sin(t*2);
 

This will move the dodecahedron up and down, by applying the sin() value to the y axis on each frame, and a little adjustment to make it look cooler. Try changing these values, to see how it affects the animations.

diff --git a/files/ru/games/tutorials/2d_breakout_game_phaser/extra_lives/index.html b/files/ru/games/tutorials/2d_breakout_game_phaser/extra_lives/index.html index b01d6bf0ac..e4602cb279 100644 --- a/files/ru/games/tutorials/2d_breakout_game_phaser/extra_lives/index.html +++ b/files/ru/games/tutorials/2d_breakout_game_phaser/extra_lives/index.html @@ -20,7 +20,7 @@ original_slug: Games/Tutorials/Создание_2D_Breakout_игры_на_Phaser

Добавьте следующие переменные сразу после всех наших текущих определений переменных:

-
var lives = 3;
+
var lives = 3;
 var livesText;
 var lifeLostText;
 
@@ -31,7 +31,7 @@ var lifeLostText;

Надписи мы уже определяли, когда реализовывали систему очков. Добавьте следующие строки кода в после определения надписи scoreText в функции create():

-
livesText = game.add.text(game.world.width-5, 5, 'Lives: '+lives, { font: '18px Arial', fill: '#0095DD' });
+
livesText = game.add.text(game.world.width-5, 5, 'Lives: '+lives, { font: '18px Arial', fill: '#0095DD' });
 livesText.anchor.set(1,0);
 lifeLostText = game.add.text(game.world.width*0.5, game.world.height*0.5, 'Life lost, click to continue', { font: '18px Arial', fill: '#0095DD' });
 lifeLostText.anchor.set(0.5);
@@ -46,12 +46,12 @@ lifeLostText.visible = false;
 
 

Как вы могли заметить, мы используем одинаковые стили для всех надписей: scoreText, livesText и lifeLostText. Однако, налицо копирование кода и если мы, когда-либо, захотим изменить размер шрифта или цвет, то нам придётся делать это в нескольких местах. Чтобы избежать этого, мы вынесем стиль в отдельную переменную. Напишите следующую строку сразу после всех наших текущих определений переменных:

-
var textStyle = { font: '18px Arial', fill: '#0095DD' };
+
var textStyle = { font: '18px Arial', fill: '#0095DD' };
 

Теперь мы можем использовать эту переменную для нашего текста — обновите ваш код и замените повторяющиеся участки со стилем текста на переменную.

-
scoreText = game.add.text(5, 5, 'Points: 0', textStyle);
+
scoreText = game.add.text(5, 5, 'Points: 0', textStyle);
 livesText = game.add.text(game.world.width-5, 5, 'Lives: '+lives, textStyle);
 livesText.anchor.set(1,0);
 lifeLostText = game.add.text(game.world.width*0.5, game.world.height*0.5, 'Life lost, click to continue', textStyle);
@@ -65,7 +65,7 @@ lifeLostText.visible = false;
 
 

Чтобы реализовать жизнь в нашей игре, давайте сначала изменим функцию шара, связанную с событием onOutOfBounds. Вместо того, чтобы выполнять анонимную функцию и сразу показывать сообщение:

-
ball.events.onOutOfBounds.add(function(){
+
ball.events.onOutOfBounds.add(function(){
     alert('Game over!');
     location.reload();
 }, this);
@@ -73,12 +73,12 @@ lifeLostText.visible = false;
 
 

Мы объявим новую функцию ballLeaveScreen; Удалим предыдущий обработчик (зачёркнутый код сверху) и заменим его следующей линией:

-
ball.events.onOutOfBounds.add(ballLeaveScreen, this);
+
ball.events.onOutOfBounds.add(ballLeaveScreen, this);
 

Мы будем уменьшать количество жизней каждый раз, когда шар выйдет за пределы окна Canvas. Добавьте функцию ballLeaveScreen() в конец кода:

-
function ballLeaveScreen() {
+
function ballLeaveScreen() {
     lives--;
     if(lives) {
         livesText.setText('Lives: '+lives);
-- 
cgit v1.2.3-54-g00ecf