javascript преобразование в интервале не работает - PullRequest
0 голосов
/ 11 июля 2020

В основном, пытаясь создать игру, в которой пользователь должен щелкнуть определенное c слово, расположенное вверху страницы, мне нужно запрограммировать 4-кнопочные html элементы, чтобы они подпрыгивали внутри контейнера div однако мое преобразование html в интервале не работает.

var upperLimitY = 360;
var lowerLimitY = 0;
var upperLimitX = 520;
var lowerLimitX = 0;
var upperVelocity = 10;
var lowerVelocity = 2;
var velocity = 5;

var wordStore = document.getElementsByClassName("word1")[0];


function startGame() {
  setInterval(moveWord, 10);
}


function moveWord() {

  if (lowerLimitX < wordStore.style.transform.x < upperLimitX && lowerLimitY <
    wordStore.style.transform.y < upperLimitY) {

    wordStore.style.transform = "translate(" + velocity + "px ," + velocity + ")";
    velocity += velocity;
  } else {
    velocity *= -1;
  }
};
<div class="wordGameContainerHeader">
  <h1>Word Wizard</h1>
  <h4>WORD TO FIND</h4>
</div>

<div class="wordGameContainer">
  <button class="word1">WORD 1</button>
  <button class="word2">WORD 2</button>
  <button class="word3">WORD 3</button>
  <button class="word4">WORD 4</button>
</div>

<div>
  <button onclick="startGame()" class="playButton">PLAY</button>
</div>

Кнопки встроены в div размером 600 x 300 пикселей, а элементы имеют ширину 80 пикселей и высоту 40 пикселей, поэтому я имеют верхний предел x до 600–80 пикселей и наоборот для пределов y. Кнопка, на которой я тестирую код, вообще не двигается.

Ответы [ 2 ]

0 голосов
/ 11 июля 2020

Проблемы с синтаксисом:

  • style.transform не имеет дополнительных свойств (x и y).

Вам придется проанализировать его самостоятельно, используя разделение или регулярное выражение.

  • Отсутствует px в части перевода y, что делает его недействительным

wordStore.style.transform = "translate(" + velocity + "px ," + velocity + "px)";

  • Условие привязки logi c (x < y < z) не действует в javascript

x < y && y < z

Логические проблемы:

  • С вашим текущим logi c, кнопки будут отскакивать назад по той же предопределенной линии
  • Как только кнопки выйдут за пределы, ваши движения остановятся, так как вы никогда не добавляете никакого значения к фактическому положению после реверсирования velocity
  • Вы могли бы использовать class как id, что нормально, но глупо

Пример с комментариями на основе вашего кода:

Примечание. полностраничный режим

var upperVelocity = 10;
var lowerVelocity = 2;
//var velocity = 5; //REM: Dropped to bring some random dynamic into it
var speed = 25; //REM: Interval-Timeout
var bounds = null;

//REM: Calculating the bounds according to the bounds of .wordGameContainer
//var upperLimitY = 360;
//var lowerLimitY = 0;
//var upperLimitX = 520;
//var lowerLimitX = 0;

//REM: Not required, since there is only one "word1"
//var wordStore = document.getElementsByClassName("word1")[0];

function startGame(){
  //REM: Calculating the bounds
  bounds = document.querySelector(".wordGameContainer").getBoundingClientRect();

  //REM: Getting all .words
  var tListOfWords = document.getElementsByClassName("word");
  for(var i=0, j=tListOfWords.length; i<j; i++){
    //REM: Clearing the current timeout, else speeds up on pressing again
    clearInterval(tListOfWords[i].dataset.Interval);
  
    //REM: x and y require different directions, else they just keep bouncing back and forth diagonally
    tListOfWords[i].dataset.Direction = JSON.stringify({x: 1, y: 1});
  
    //REM: Storing the return of setInterval() to clear it eventually
    //REM: Binding the element instead, so that moveWord() can be used for all words the same
    tListOfWords[i].dataset.Interval = setInterval(moveWord.bind(null, tListOfWords[i]), speed);
    
    //REM: Adding event to stop the movement
    //REM: Using onmouseup to omit keyboard input (tab + enter)
    tListOfWords[i].onmouseup = function(){
      clearInterval(this.dataset.Interval);
      alert(this.id)
    }
  }
};

//REM: The .word not gets passed as parameter "element"
function moveWord(element){
  //REM: style.transform has no sub properties
  //REM: Using getBoundingClientRect() so the buttons entirely stay inside the box
  var tPosition = element.getBoundingClientRect(),
      tDirection = JSON.parse(element.dataset.Direction);

  //REM Calculate the movement according to upperVelocity and lowerVelocity
  //REM: Using different velocities for x, y to make less predictable and more dynamic
  var tMovementX = Math.floor(Math.random() * (upperVelocity - lowerVelocity) + lowerVelocity),
      tMovementY = Math.floor(Math.random() * (upperVelocity - lowerVelocity) + lowerVelocity);

  //REM: Adding the direction of the element
  tMovementX *= tDirection.x;
  tMovementY *= tDirection.y;

  //REM: Checking x
  if(
    (tPosition.left + tMovementX) <= bounds.left || 
    (tPosition.right + tMovementX) >= bounds.right
  ){
    tDirection.x *= -1;
    tMovementX *= -1;
    
    //REM: Storing the changed direction
    element.dataset.Direction = JSON.stringify(tDirection)
  };
  
  //REM: Checking y
  if(
    (tPosition.top + tMovementY) <= bounds.top ||
    (tPosition.bottom + tMovementY) >= bounds.bottom
  ){
    tDirection.y *= -1;
    tMovementY *= -1;
    
    //REM: Storing the changed direction
    element.dataset.Direction = JSON.stringify(tDirection)
  };

  //REM: Getting the actual left/top assigned to the style
  //REM: Note that those are not the same values as tPosition.
  var tLeftInsideParent = (parseFloat(element.style.left) || 0),
      tTopInsideParent = (parseFloat(element.style.top) || 0);

  element.style.left = tLeftInsideParent + tMovementX + "px";
  element.style.top = tTopInsideParent + tMovementY + "px"
};

//REM: Adjusting the bounds on scrolling and resizing
window.onscroll = window.onresize = function(){
  //REM: Calculating the bounds
  bounds = document.querySelector(".wordGameContainer").getBoundingClientRect()
};
.word{
  position: relative
}

.wordGameContainer{
  background: #1390ff;
  height: 150px;
  width: 400px;
}
<div class="wordGameContainerHeader">
  <h1>Word Wizard</h1>
  <h4>WORD TO FIND</h4>
</div>

<div>
  <button onclick="startGame()" class="playButton">PLAY</button>
</div>

<div class="wordGameContainer">
  <!--REM: Why is the "class" used like an "id"? -->
  <button id="word1" class="word">WORD 1</button>
  <button id="word2" class="word">WORD 2</button>
  <button id="word3" class="word">WORD 3</button>
  <button id="word4" class="word">WORD 4</button>
</div>

Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling.. Some text to enable scrolling..
0 голосов
/ 11 июля 2020

Вы пропустили запись px во втором параметре функции moveWord. Я установил 1 в функции setInterval, чтобы переводить слово в замедленном режиме, чтобы вы могли видеть, что слово переводится. Вот и все.

Примечание: Я только что проверил, почему ваше преобразование не работает. Больше ничего не проверял.

function startGame() {
  setInterval(moveWord, 1000); // use 1s for translating slow.
}

function moveWord() {

  if (lowerLimitX < wordStore.style.transform.x < upperLimitX && lowerLimitY <
    wordStore.style.transform.y < upperLimitY) {

    wordStore.style.transform = "translate(" + velocity + "px ," + velocity + "px)";
    velocity += velocity;
  } else {
    velocity *= -1;
  }
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...