Мяч не прыгает

Итак, я создаю HTML-файл, но... мяч вообще не прыгает! вот код, если кто-то может помочь:

let dy = 2; // vertical speed
let interval;
let y; // Declare y outside the event listener function
let collision = false;

function startGame() {
  let circle = document.querySelector('.circle');
  y = parseInt(circle.style.top) || 10; // Initial top position
  let pad = document.querySelector('.pad');
  let padTop = window.innerHeight - pad.offsetHeight; // Get the top position of the pad

  console.info("Pad height:", pad.offsetHeight);
  console.info("Pad top position:", padTop);

  interval = setInterval(function() {
    // Check if the circle reaches the top of the pad
    if (y + circle.offsetHeight >= padTop) {
      clearInterval(interval); // Stop the circle
      dy = 0; // Reset vertical speed
      collision = true;
      circle.style.top = (padTop - circle.offsetHeight) + 'px'; // Correct position
      console.info("touchè")
    } else {
      collision = false; // Circle is not colliding with the pad
      // Move the circle downwards
      y += dy;
    }

    // Update circle position
    circle.style.top = y + 'px';
  }, 10); // Move every 10 milliseconds
}

// Add event listener for space bar key press
document.addEventListener('keydown', function(event) {
  if (event.code === 'Space') {
    console.info(y);
    let circle = document.querySelector('.circle');
    if (collision) { // Only allow jumping when the circle is on the pad
      dy = -10; // Set the vertical speed to -10 to make the circle jump upwards
    } else {
      console.info("Nuh uh, jump when on pod. this ain't your double jump type shi..."); // Inform the user that jumping is only allowed when on the pad
    }
  }
});
body {
  background-color: royalblue;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans';
  margin: 0;
  /* Remove default margin */
  padding: 0;
  /* Remove default padding */
  cursor: default;
  position: relative;
  /* Add position relative to the body */
  height: 100vh;
  /* Ensure body takes full viewport height */
}

.button {
  background-color: rgb(0, 153, 255);
  border-radius: 10px;
  /* Adjust the radius as needed */
  font-family: 'Ubuntu', sans-serif;
  position: absolute;
  height: 100px;
  width: 100px;
  text-decoration: solid;
  top: 20px;
  /* Adjust as needed */
  right: 20px;
  /* Adjust as needed */
  cursor: pointer;
  /* Change cursor on hover */
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  /* Optional: to make the text visible on the button */
  text-align: center;
  /* Optional: to center the text */
}

.circle {
  background-color: dodgerblue;
  border-radius: 100%;
  height: 100px;
  width: 100px;
  position: absolute;
  top: 10px;
  /* Initial top position */
  left: 10px;
  /* Initial left position */
}

.pad {
  background-color: rgb(0, 25, 105);
  /* Changed color for better visibility */
  border-radius: 40px;
  width: 100%;
  height: 50px;
  /* Increased height for better visibility */
  position: absolute;
  bottom: 0;
  /* Position it at the bottom */
  border: 2px solid black;
  /* Add a border to make it stand out */
  z-index: 10;
  /* Ensure it's on top of other elements */
  text-align: center;
  /* Center text inside pad */
  line-height: 50px;
  /* Center text vertically */
}
<!DOCTYPE html>
<html lang = "en">
<head>
  <meta charset = "UTF-8">
  <title>Idle Game!</title>
</head>
<body>
  <div class = "pad">Pad</div>
  <div class = "circle"></div>
  <div class = "button" onclick = "startGame()">Start the game!</div>
</body>
</html>

я пытался добавить Y в event.key для пробела, НО ТОГДА ОНО НЕ ПАДАЕТ! Я также попытался выполнить проверку столкновений (которая сработала), но она все еще не работает! Почему буква Y меняется, а круг остается на том же месте? Пожалуйста, кто-нибудь, помогите мне!

Под «прыжком» вы подразумеваете движения вверх-вниз? Кажется, что вы очищаете интервал, если мяч находится на площадке и останавливаете движение clearInterval(interval); // Stop the circle;

Mrmld Sky 10.06.2024 19:47
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
Поведение ключевого слова "this" в стрелочной функции в сравнении с нормальной функцией
В JavaScript одним из самых запутанных понятий является поведение ключевого слова "this" в стрелочной и обычной функциях.
Концепция локализации и ее применение в приложениях React ⚡️
Концепция локализации и ее применение в приложениях React ⚡️
Локализация - это процесс адаптации приложения к различным языкам и культурным требованиям. Это позволяет пользователям получить опыт, соответствующий...
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
Улучшение производительности загрузки с помощью Google Tag Manager и атрибута Defer
В настоящее время производительность загрузки веб-сайта имеет решающее значение не только для удобства пользователей, но и для ранжирования в...
Безумие обратных вызовов в javascript [JS]
Безумие обратных вызовов в javascript [JS]
Здравствуйте! Юный падаван 🚀. Присоединяйся ко мне, чтобы разобраться в одной из самых запутанных концепций, когда вы начинаете изучать мир...
Система управления парковками с использованием HTML, CSS и JavaScript
Система управления парковками с использованием HTML, CSS и JavaScript
Веб-сайт по управлению парковками был создан с использованием HTML, CSS и JavaScript. Это простой сайт, ничего вычурного. Основная цель -...
JavaScript Вопросы с множественным выбором и ответы
JavaScript Вопросы с множественным выбором и ответы
Если вы ищете платформу, которая предоставляет вам бесплатный тест JavaScript MCQ (Multiple Choice Questions With Answers) для оценки ваших знаний,...
1
1
56
1
Перейти к ответу Данный вопрос помечен как решенный

Ответы 1

Ответ принят как подходящий

Поскольку вы удалили тайм-аут, установка скорости y не имеет никакого эффекта. Кроме того, даже если скорость y равна -10, вы сначала проверяете столкновение, чтобы скорость снова была установлена ​​на 0.

  • просто продолжай интервал
  • начните интервал с обновления позиции

Несколько советов:

  • Для анимации лучше использовать requestAnimationFrame, чем setInterval.
  • Для анимации гораздо проще использовать style.transform.translate() для позиционирования мяча.

let dy = 2; // vertical speed
let interval;
let y; // Declare y outside the event listener function
let collision = false;
let circle = document.querySelector('.circle');


function startGame() {
  y = parseInt(circle.style.top) || 10; // Initial top position
  let pad = document.querySelector('.pad');
  let padTop = window.innerHeight - pad.offsetHeight; // Get the top position of the pad

  console.info("Pad height:", pad.offsetHeight);
  console.info("Pad top position:", padTop);

  interval = setInterval(function() {
y += dy;

  
// Check if the circle reaches the top of the pad
if (y + circle.offsetHeight >= padTop) {
  dy = 0; // Reset vertical speed
  collision = true;
  circle.style.top = (padTop - circle.offsetHeight) + 'px'; // Correct position
  console.info("touchè")
} else {
  collision = false; // Circle is not colliding with the pad
  // Move the circle downwards
}

// Update circle position
circle.style.top = y + 'px';
  }, 10); // Move every 10 milliseconds
}

// Add event listener for space bar key press
document.addEventListener('keydown', (event) => {
  console.info(event.code)
  if (event.code === 'Space') {
if (collision) { // Only allow jumping when the circle is on the pad
  dy = -10; // Set the vertical speed to -10 to make the circle jump upwards
} else {
  console.info("Nuh uh, jump when on pod. this ain't your double jump type shi..."); // Inform the user that jumping is only allowed when on the pad
}
  }
});
body {
  background-color: royalblue;
  font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans';
  margin: 0;
  /* Remove default margin */
  padding: 0;
  /* Remove default padding */
  cursor: default;
  position: relative;
  /* Add position relative to the body */
  height: 100vh;
  /* Ensure body takes full viewport height */
}

.button {
  background-color: rgb(0, 153, 255);
  border-radius: 10px;
  /* Adjust the radius as needed */
  font-family: 'Ubuntu', sans-serif;
  position: absolute;
  height: 100px;
  width: 100px;
  text-decoration: solid;
  top: 20px;
  /* Adjust as needed */
  right: 20px;
  /* Adjust as needed */
  cursor: pointer;
  /* Change cursor on hover */
  display: flex;
  justify-content: center;
  align-items: center;
  color: white;
  /* Optional: to make the text visible on the button */
  text-align: center;
  /* Optional: to center the text */
}

.circle {
  background-color: dodgerblue;
  border-radius: 100%;
  height: 100px;
  width: 100px;
  position: absolute;
  top: 10px;
  /* Initial top position */
  left: 10px;
  /* Initial left position */
}

.pad {
  background-color: rgb(0, 25, 105);
  /* Changed color for better visibility */
  border-radius: 40px;
  width: 100%;
  height: 50px;
  /* Increased height for better visibility */
  position: absolute;
  bottom: 0;
  /* Position it at the bottom */
  border: 2px solid black;
  /* Add a border to make it stand out */
  z-index: 10;
  /* Ensure it's on top of other elements */
  text-align: center;
  /* Center text inside pad */
  line-height: 50px;
  /* Center text vertically */
}
<!DOCTYPE html>
<html lang = "en">
<head>
  <meta charset = "UTF-8">
  <title>Idle Game!</title>
</head>
<body>
  <div class = "pad">Pad</div>
  <div class = "circle"></div>
  <div class = "button" onclick = "startGame()">Start the game!</div>
</body>
</html>

На самом деле ваш JS заставляет мяч прыгать вечно. я хочу, чтобы мяч подпрыгнул, а затем упал. Но этот код решает проблему, о которой я просил, спасибо!

Memelian4 10.06.2024 19:54

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

Kokodoko 10.06.2024 21:12

Другие вопросы по теме