一个开关条件不起作用,而另一个条件不起作用

One switch condition doesn't work while another does

本文关键字:条件 不起作用 另一个 开关 一个      更新时间:2023-09-26

我正在屏幕上制作一种果蝇,但经过编程。首先,我写下了非常大的代码,但我发现有些不对劲。果蝇只向左移动,而不向右移动。

代码"向右 90 度":

case 90:
    fly.style.marginLeft = (parseInt(left) + sw).toString();
break;

代码"向左 270 度":

case 270:
    fly.style.marginLeft = (parseInt(left) - sw).toString();
break;
90度

工作,270度工作,但为什么90度不起作用?我只看到"+"与"-"不同,整个代码:

document.body.innerHTML = document.body.innerHTML + "<img id='fly' onclick='hi();' src='http://screen-bug.googlecode.com/git/fruitfly-moving.gif'>";
var fly = document.getElementById("fly");
var rotation = 0;
var ramargintop = Math.floor(Math.random() * screen.height);
var ramarginleft = Math.floor(Math.random() * screen.width);
fly.style.marginTop = ramargintop;
fly.style.marginLeft = ramarginleft;
var interval = setInterval(movefly, 50);
function movefly(){
//    rotation += Math.floor((Math.random() * 20) - 9.46);
    if(rotation < 0){
        rotation += 360;
    }else if(rotation > 360){
        rotation -= 360;
    }
    fly.style.transform = "rotate(" + rotation + "deg)";
    moveflyforward();
 }
function moveflyforward(){
    var topa = fly.style.marginTop;
    var left = fly.style.marginLeft;
    var sw = 0.2;
    switch(rotation){
        case 0:
            fly.style.marginTop = (parseInt(topa) - sw).toString();
        break;
        case 90:
            fly.style.marginLeft = (parseInt(left) + sw).toString();
        break;
        case 180:
            fly.style.marginTop = (parseInt(topa) + sw).toString();
        break;
        case 270:
            fly.style.marginLeft = (parseInt(left) - sw).toString();
        break;
        case 360:
            fly.style.marginTop = (parseInt(topa) - sw).toString();
        break;
        default:
            document.body.innerHTML = "<font color='red' size='30'>Error on fly, please contact Ebbe.z@live.nl about this. CODE: MoveForwardSwitch</font>";
        break;
    }
}

问题是使用parseInt

假设left是 10(sw是 0.2(

当您将 0.2 加到 10 时,结果将在下次运行时10.2 left再次为 10(并且没有任何反应(,因为 parseInt 返回一个整数。

当您从 10 中减去 0.2 时,结果将是 9.8 ,在下一次运行时,left将是 9(也不是所需的结果(。

使用 parseFloat 而不是 parseInt(当您想使用浮点数时(或将sw设置为整数,例如 1