1. Home
  2. Docs
  3. General Programming
  4. Control Flow, If-Else block

Control Flow, If-Else block

There are times when we would like to perform different set of tasks according to a given state, for example: let’s say we would like to change a Sphere’s moving direction when it hits the boundaries. We can do something like this:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
s is a Sphere having material="rock"
var direction=1, position=0
do 100 times
  position=position+0.05*direction
  s.move(x+0.05*direction) in 0.05 seconds
 
  // change direction when hit horizontal boundaries
  if(position>1 or position<-1) then do
    direction=direction*-1
  end do

  // print the current position
  sys.print position
 
end do

In the above sample code we check whether the position is greater than 1 or less than -1 and change the movement direction by multiplying the direction variable by -1
Now let’s change the position printing color to according to the movement direction. In order to do that we need to use the Else switch statement:


1
2
3
4
5
6
if (direction==1) then do
  sys.print position, color=blue
end do else
do
  sys.print position, color=red
end do

We just used the If and Else switches. If the direction is positive (1) we print in blue otherwise we print in red.
Here is the final code:


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
s is a Sphere having material="rock"
var direction=1, position=0

do 100 times
  position=position+0.05*direction
  s.move(x+0.05*direction) in 0.05 seconds
 
  // change direction when hit horizontal boundaries
  if(position>1 or position<-1) then do
    direction=direction*-1
  end do

  // print the current position in red or blue
  if (direction==1) then do
    sys.print position, color=blue
  end do else
  do
    sys.print position, color=red
  end do
 
end do
Was this article helpful to you? Yes No

How can we help?