【发布时间】:2021-07-21 05:58:21
【问题描述】:
我正在尝试在田野中向上(向北)、向下(向南)、向左(向西)和向右(向东)移动一头牛(每次移动 10 像素)。在我收集了一组基本方向后,我设置了奶牛的 style.left 和 style.up 并根据数组中的方向旋转它。
如何让奶牛先向一个方向旋转,然后再向它移动,然后再向另一个方向旋转,然后再向它移动?现在,假设数组中有 3 个北方向:奶牛将移动整个 30 像素而不是每次移动 10 像素。如果有东西方向和南方向,则牛不会向东旋转并向东移动 10px,然后向南旋转并向南移动 10px。奶牛在旋转和移动之前接收到一系列方向是很重要的。
const cow = {
directions: ['North', 'East'],
addDirection(direction) {
this.directions.push(direction);
}
};
let num = 0; // will increment or decrement by 90 or 180
let key = null; // keep track of keys to determine how much to increment or decrement
cow.directions.forEach(direction => {
switch(direction) {
case 'North':
if(!key) {
cowEl.style.transform = 'rotate(0deg)';
}
else if(key === 'East') {
num -= 90;
cowEl.style.transform = `rotate(${num}deg)`;
}
else if(key === 'West') {
num += 90;
cowEl.style.transform = `rotate(${num}deg)`;
}
else if(key === 'South') {
num -= 180;
cowEl.style.transform = `rotate(${num}deg)`;
}
key = direction; // North
// setTimeout(() => cowEl.style.top = parseInt(cowEl.style.top) - moveBy + 'px', 1000);
cowEl.style.top = parseInt(cowEl.style.top) - moveBy + 'px';
break;
case 'East':
if(!key || key === 'North') {
num += 90;
cowEl.style.transform = `rotate(${num}deg)`;
}
else if(key === 'South') {
num -= 90;
cowEl.style.transform = `rotate(${num}deg)`;
}
else if(key === 'West') {
num -= 180;
cowEl.style.transform = `rotate(${num}deg)`;
}
key = direction; // East
// setTimeout(() => cowEl.style.left = parseInt(cowEl.style.left) + moveBy + 'px', 2000);
cowEl.style.left = parseInt(cowEl.style.left) + moveBy + 'px';
break;
case 'South':
if(!key || key === 'North') {
num += 180;
cowEl.style.transform = `rotate(${num}deg)`;
}
else if(key === 'East') {
num += 90;
cowEl.style.transform = `rotate(${num}deg)`;
}
else if(key === 'West') {
num -= 90;
cowEl.style.transform = `rotate(${num}deg)`;
}
key = direction; // South
cowEl.style.top = parseInt(cowEl.style.top) + moveBy + 'px';
break;
case 'West':
if(!key || key === 'North') {
num -= 90;
cowEl.style.transform = `rotate(${num}deg)`;
}
else if(key === 'South') {
num += 90;
cowEl.style.transform = `rotate(${num}deg)`;
}
else if(key === 'East') {
num += 180;
cowEl.style.transform = `rotate(${num}deg)`;
}
key = direction; // West
cowEl.style.left = parseInt(cowEl.style.left) - moveBy + 'px';
break;
}
});
【问题讨论】:
-
请至少添加您的相关代码
-
您使用的是 CSS 动画还是 Javascript + 计时?请阅读 [link]stackoverflow.com/help/minimal-reproducible-example,因为如果我们看不到您是如何尝试实现的,我们只会猜测解决方案。
-
我已经添加了代码。
标签: javascript html css css-position execution