javascript - Javascript 移动球练习
问题描述
我需要一些帮助来理解上周我的开发训练营让我们完成的练习的解决方案。问题很简单,在对角线轨迹上来回移动“球”(在 html 中的“div”中创建)。下面是解决方案。我无法理解的是最后的“if”语句。根据解,如果球的位置等于 0 或大于由 Xmax 或 Ymax 定义的边缘,则 reverse = !reverse。由于 reverse 最初设置为 false 作为全局变量,这是否意味着如果满足这些条件,则 reverse 的全局值会发生变化?
// BALL MOVING EXERCISE (WEEK 2) //
//Set global variable that would contain the position, velocity and the html element "ball"
// CREATE DIV "BALL" IN HTML - COPY/PASTE TO BODY TAG
#ball{
height: 50px;
width : 50px;
background : black;
border-radius : 50%;
position : absolute;
left: ;
top: ;
}
var positionX = 0;
var positionY = 0;
var velocity = 100;
var reverse = false;
var ball = document.getElementById("ball");
//write a function that can change the position of the html element "ball"
function moveBall() {
// two x-axis coordinates
var Xmin = 0;
var Xmax = 300;
// two y-axis coordinates
var Ymin = 0;
var Ymax = 300;
if (reverse) {
positionX = positionX - velocity;
positionY = positionY - velocity;
ball.style.left = positionX + "px";
ball.style.top = positionY + "px";
} else {
positionX = positionX + velocity;
positionY = positionY + velocity;
ball.style.left = positionX + "px";
ball.style.top = positionY + "px";
}
if (
positionX > Xmax ||
positionX === Xmin ||
positionY > Ymax ||
positionY === Ymin
) {
reverse = !reverse;
}
}
setInterval(moveBall, 100);
解决方案
推荐阅读
- python - 未能获得正整数
- cocoa - 光标奇怪的行为:重置为默认值
- json.net - SwaggerUI 5.0.0 忽略 JsonProperty 名称
- python - 在 Ubuntu 16.04 Python 3.7 中,这些要求无法为 Odoo 13 安装
- python - 如何使用 Python 将 Web 服务的非常大的 JSON 响应转换为 CSV?
- android - 如何在游戏结束屏幕上显示最终分数和高分?
- titan - 没有方法签名:org.janusgraph.graphdb.database.management.JanusGraphIndexWrapper.buildCompositeIndex()
- mysql - 从mysql数据库中获取两个数字之间的缺失数字
- r - 按分钟合并推文
- machine-learning - 为什么它给我“预期的二维数组,而不是一维数组”的错误