Adapt the flying height of the \l;winged shooter\u object\botfj; to the terrain.
\t;Program
Here is one more time the program of the previous exercise that hunts ants:
\c;
\s;extern void object::JetFighter1()
\s;{
\s; object item;
\s;
\s; aim(-20);
\s; jet(0.2);
\s; while (position.z < 10)
\s; {
\s; wait(0.2);
\s; }
\s; jet(0);
\s;
\s; while (true)
\s; {
\s; while (radar(AlienAnt, 0, 360, 0, 20) == null)
\s; {
\s; item = radar(AlienAnt);
\s; turn(direction(item.position));
\s; motor(1,1);
\s; wait(0.2);
\s; }
\s; fire(1);
\s; }
\s;}
\n;
The bot always stays at an altitude of 10m above sea level. This is not adapted to the mountainous terrain of the present exercise, the bot has got to adapt to the terrain. The best way to do so is to insert just before the \c;wait(0.2);\n; a test to see if the height above ground is too low or too high, and to react accordingly.
We already saw that \c;position.z\n; gives the altitude above sea level. \c;\l;topo\u cbot\topo;(position)\n; gives the altitude of the ground at the position of the bot. If we want the bot to stay at an altitude between 6 and 9m above ground, we must treat the following cases: if \c;position.z-topo(position)\n; is smaller than 6, the bot must climb with \c;jet(1);\n;. If \c;position.z-topo(position)\n; is greater than 9, the bot must go down with \c;jet(-1);\n;. In order to program these tests, use the instruction \c;\l;if\u cbot\if;\n;, that executes the instructions in braces only once if the condition is true:
\c;
\s; jet(0);
\s; if (position.z-topo(position) < 6)
\s; {
\s; jet(1);
\s; }
\s;
\s; if (position.z-topo(position) > 9)
\s; {
\s; jet(-1);
\s; }
\n;
Before starting the testing, stabilize the altitude with \c;jet(0);\n;: in case the height above ground lies between 6 and 9m, the bot must neither climb nor go down. If afterwards either \c;jet(1);\n; or \c;jet(-1);\n; is executed, it will cancel the previous \c;jet(0);\n;.
Just insert these lines before the \c;wait(0.2)\n;, and the bot will adapt to the terrain. You can then delete the first lines of the program that set the initial altitude at 10m.
\t;See also
\l;Programming\u cbot;, \l;types\u cbot\type; and \l;categories\u cbot\category;.