我正在尝试用 switch 语句替换 if 和 else if 语句。
Ball 类来自一个外部 ActionScript 文件,女巫有一个变量,我在其中传递球半径(半径 = 30)。
如何将 if 和 else if 语句转换为 switch 语句?
编码:
private var ball:Ball;
private var left:Number = 0;
private var right:Number = stage.stageWidth;
private var top:Number = 0;
private var bottom:Number = stage.stageHeight;
if(ball.x >= right + ball.radius)
{
ball.x = left - ball.radius;
}
else if(ball.x <= left - ball.radius)
{
ball.x = right + ball.radius;
}
if(ball.y >= bottom + ball.radius)
{
ball.y = top - ball.radius;
}
else if(ball.y <= top - ball.radius)
{
ball.y = bottom + ball.radius;
}
谢谢你
最佳答案
这有一个小技巧 - 你在 case 而不是 switch 处评估不等式:
switch(true) {
case ball.x >= right + ball.radius:
ball.x = left - ball.radius;
break;
case ball.x <= left - ball.radius:
ball.x = right + ball.radius;
break;
}
switch(true){
case (ball.y >= bottom + ball.radius):
ball.y = top - ball.radius;
break;
case (ball.y <= top - ball.radius):
ball.y = bottom + ball.radius;
break;
}
关于actionscript-3 - AS3 用 switch 语句替换 if 和 else if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13748364/