可汗学院:If 语句 2

Khan Academy: If Statements 2

我的 if 语句不起作用,就像上次一样,但这次我的 if 语句中的行不会 x = x - 2;(我没有做 else if 因为我认为这是问题所在). Link:https://www.khanacademy.org/computer-programming/probability/5609184564559872。代码:

var x = 78;
var y = 18;

// Just in case I test
var saveX = 78;
var saveY = 18;

draw = function() {
    background(150, 255, 250);
    
    strokeWeight(1);
    stroke(0, 0, 0);
    rect(78, 20, 254, 25);
    
    strokeWeight(6);
    stroke(255, 0, 0);
    line(x, y, x, y + 29);
    
    
    if (x > 332) {
        x = x - 2;
    }
    
    if (x < 78) {
        x = x + 2;
    }
    
    x = x + 2;
};

有效,x = x+2 使值完全不变

这就是你想要的ping-pong效果,关键是方向变量。

var x = 78;
var y = 18;

// Just in case I test
var saveX = 78;
var saveY = 18;
var direction = 1;

draw = function() {
    background(150, 255, 250);
    
    strokeWeight(1);
    stroke(0, 0, 0);
    rect(78, 20, 254, 25);
    
    strokeWeight(6);
    stroke(255, 0, 0);
    line(x, y, x, y + 29);
    
    
    if (x > 332) {
        direction = -1;
    }
    
    if (x < 78) {
        direction = 1;
    }
    
    x = x + direction * 2;
};