AS3使用switch语句替换if和else if

时间:2012-12-06 16:42:59

标签: actionscript-3 switch-statement

我正在尝试使用开关语句替换 if else if 语句。

Ball类来自一个外部动作脚本文件,该文件有一个变量,我传入球半径(半径= 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;
    } 

谢谢

2 个答案:

答案 0 :(得分:3)

这有一个小技巧 - 你在不是开关的情况下评估不平等:

 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;
} 

答案 1 :(得分:1)

将switch语句视为荣耀的IF 基本上,您正在评估case语句中的switch语句 切换语句以自上而下的顺序进行评估,因此一旦找到匹配,它将在运行该代码后的代码中断开。
此外,在您的情况下,您希望将X和Y分开(

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;
  default:
    // no match
}

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;
  default:
    // no match
} 
相关问题