Итак, я создаю 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 меняется, а круг остается на том же месте? Пожалуйста, кто-нибудь, помогите мне!



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Поскольку вы удалили тайм-аут, установка скорости 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 заставляет мяч прыгать вечно. я хочу, чтобы мяч подпрыгнул, а затем упал. Но этот код решает проблему, о которой я просил, спасибо!
Да, вы все еще можете многое улучшить, чтобы создать реалистичный прыгающий мяч :) Например, чем ближе позиция y к потолку, тем медленнее скорость.
Под «прыжком» вы подразумеваете движения вверх-вниз? Кажется, что вы очищаете интервал, если мяч находится на площадке и останавливаете движение
clearInterval(interval); // Stop the circle;