Advertisement
terorama

Flash / Tutorials 6

Apr 2nd, 2013
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. -------------------------------------------------------
  2. -------------------------------------------------------
  3. -------------------------------------------------------
  4. -------------------------------------------------------
  5. // Create a number of trees randomly
  6. // positioned within the document
  7. function createTrees(numberOfTrees:int):void {
  8.  
  9.  // variable to store trees created
  10.  // in the loop - the DisplayObject
  11.  // type satisfies both MovieClip
  12.  // and Bitmap instances
  13.  var currTree:DisplayObject;
  14.  
  15.  // loop through the number of trees
  16.  while(numberOfTrees--){
  17.  
  18.   // randomly add a tree either
  19.   // as a bitmap or a movie clip
  20.   if (Math.random() < .5) {
  21.    
  22.    // create a new Tree instance
  23.    // Tree is the class name given to
  24.    // the tree symbol in the library
  25.    currTree = new Tree();
  26.    
  27.   }else{
  28.  
  29.    // create the tree BitmapData instance
  30.    // from the library, then add it to a
  31.    // new Bitmap instance
  32.    var currTreeData:TreeImageData = new TreeImageData(0, 0);
  33.    currTree = new Bitmap(currTreeData);
  34.   }
  35.  
  36.   // position the new instance randomly on
  37.   // the screen based on the stage's size.
  38.   // subtracting the tree size from the stage
  39.   // size keeps the trees on screen
  40.   currTree.x = Math.random() * (stage.stageWidth - currTree.width);
  41.   currTree.y = Math.random() * (stage.stageHeight - currTree.height);
  42.   // don't forget to add the tree
  43.   // to the display list
  44.   addChild(currTree);
  45.  }
  46. }
  47.  
  48. -------------------------------------------------------
  49. -------------------------------------------------------
  50. -------------------------------------------------------
  51. -------------------------------------------------------
  52.  
  53. // Arrange all children in the specified
  54. // container based on their y value
  55. function sortChildrenByY(container:MovieClip):void {
  56.  var i:int;
  57.  var childList:Array = new Array();
  58.  
  59.  // first put all children in an array
  60.  i = container.numChildren;
  61.  while(i--){
  62.   childList[i] = container.getChildAt(i);
  63.  }
  64.  
  65.  // next, sort the array based on the
  66.  // elements' y property
  67.  childList.sortOn("y", Array.NUMERIC);
  68.  
  69.  // now match the arrangement of the array
  70.  // with the arrangement of the display list
  71.  i = container.numChildren;
  72.  while(i--){
  73.  
  74.   // if the child at position i in the array
  75.   // does not match the child at position
  76.   // i in the display list, set that child
  77.   // to the i position in the display list
  78.   if (childList[i] != container.getChildAt(i)){
  79.    container.setChildIndex(childList[i], i);
  80.   }
  81.  }
  82. }
  83.  
  84. / Create an instance of a library bitmap
  85. // given the Class name of MyImage
  86. var imageData:MyImage = new MyImage(0, 0);
  87. // Give the instance to a Bitmap through its
  88. // constructor, then add it to the display list
  89. var imageBmp:Bitmap = new Bitmap(imageData);
  90. addChild(imageBmp);
  91.  
  92.  
  93. // Add movie clip from the library to display list
  94. var myMovie:CustomMovieClass = new CustomMovieClass();
  95. addChild(myMovie);
  96. // Remove movie clip from the library from display list
  97. removeChild(myMovie);
  98.  
  99.  
  100. -------------------------------------------------------
  101. -------------------------------------------------------
  102. -------------------------------------------------------
  103. -------------------------------------------------------
  104. particle._visible = false;
  105. for (z = 0; z < 200; z++) {
  106.     var dupe = particle.duplicateMovieClip("s" + z, z);
  107.     dupe._x = Math.random() * 550;
  108.     dupe._y = Math.random() * 200;
  109.     dupe._xscale = dupe._yscale = Math.random() * 50 + 50;
  110.     dupe._rotation = Math.random() * 360;
  111.     dupe._alpha = Math.random() * 100;
  112. }
  113.  
  114. //------------------------------------
  115.  
  116. function _fill(obj) {
  117.     obj._x = Math.random() * 550;
  118.     obj._y = Math.random() * 200;
  119.     obj._xscale = obj._yscale = Math.random() * 50 + 50;
  120.     obj._rotation = Math.random() * 360;
  121.     obj._alpha = Math.random() * 100;
  122. }
  123. //------------------------------------
  124.  
  125. // заполняем первый этаж "мусором"
  126. for (z = 1; z < 200; z++) {
  127.     var tmp = bg.particle.duplicateMovieClip("s" + z, z);
  128.     _fill(tmp);
  129.     tmp.gotoAndStop(Math.round(Math.random() * 2) + 1);
  130. }
  131.  
  132. // второй этаж - травой
  133. for (z = 201; z < 400; z++) {
  134.     var tmp = bg.particle.duplicateMovieClip("s" + z, z);
  135.     _fill(tmp);
  136.     tmp.gotoAndStop(Math.round(Math.random() * 2) + 4);
  137. }
  138.  
  139. // третий этаж ромашками
  140. for (z = 401; z < 500; z++) {
  141.     var tmp = bg.particle.duplicateMovieClip("s" + z, z);
  142.     _fill(tmp);
  143.     tmp.gotoAndStop(6);
  144. }
  145.  
  146. var tmp_bitmap = new flash.display.BitmapData(550, 200, false, 0x00000000);
  147. bg_rastr1 = this.createEmptyMovieClip("bg2", 10000);
  148. bg_rastr2 = this.createEmptyMovieClip("bg3", 10001);
  149.  
  150. tmp_bitmap.draw(bg);
  151. bg_rastr1.attachBitmap(tmp_bitmap,10002);
  152. bg_rastr2.attachBitmap(tmp_bitmap,1003);
  153. bg_rastr2._xscale = 400;
  154. bg_rastr2._yscale = 400;
  155.  
  156. //маскируем увеличенную копию
  157. bg_rastr2.setMask(this._mask);
  158.  
  159. //И удаляем оригинал с векторным изображением нашего фона
  160. bg.swapDepths(10004);
  161. bg.removeMovieClip();
  162.  
  163. -------------------------------------------------------
  164. -------------------------------------------------------
  165. -------------------------------------------------------
  166. -------------------------------------------------------
  167. //массив с платформами
  168. var boxes = [];
  169. //каждая платформа при старте вызывает эту функцию и передаёт себя как параметр
  170. addBox = function (obj) {
  171.     boxes.push(obj);
  172. }
  173.  
  174. //--------------------------------
  175. //сила гравитации
  176. var grav = 1;
  177. //начальная скорость прыжка
  178. var jumpSpeed = -11.9;
  179. //шаг по Х
  180. var speedX = 5;
  181. //шаг по Y
  182. var speedY = 0;
  183.  
  184. //максимальная скорость падения
  185. var maxSpeedY = 14;
  186. //половина ширины персонажа
  187. var hhx = (hero.p1._x - hero.p3._x + hero.p1._width / 2 + hero.p3._width / 2) / 2;
  188. //половина высоты персонажа
  189. var hhy = (hero.p2._y - hero.p4._y + hero.p2._height / 2 + hero.p4._height / 2) / 2;
  190. //отображает состояние прыжка
  191. var jump = false;
  192. //отображает состояние удара
  193. var shoot = false;
  194.  
  195. Key.addListener(this);
  196. onKeyDown = function () {
  197.     //прыгаем
  198.     if (Key.isDown(Key.UP) && !jump && !shoot) {
  199.         jump = true;
  200.         speedY = jumpSpeed;
  201.     }
  202.     //бъём
  203.     if (Key.isDown(Key.SPACE) && !jump && !shoot) {
  204.         shoot = true;
  205.         hero.gotoAndStop(1);
  206.         hero.man.body.gotoAndPlay(2);
  207.     }
  208. };
  209.  
  210. function stepHero() {
  211.     if (!shoot) {
  212.         //смещаемся влево/вправо
  213.         if (Key.isDown(Key.LEFT)) {
  214.             hero._xscale = -100;
  215.             hero._x -= (jump) ? speedX * .8 : speedX;
  216.         } else if (Key.isDown(Key.RIGHT)) {
  217.             hero._xscale = 100;
  218.             hero._x += (jump) ? speedX * .8 : speedX;
  219.         }
  220.     }
  221.     //применяем по цепочке: гравитация -> скорость -> _y
  222.     speedY += grav;
  223.     speedY = (speedY > maxSpeedY) ? maxSpeedY : speedY;
  224.     hero._y += speedY;
  225.  
  226.     //проверка на пересечение с платформами
  227.     checkHitPlatform();
  228.  
  229.     //если закомментировать строку ниже, то можно будет свалиться с платформы
  230.     //и прыгнуть оттолкнувшись от воздуха. Этой строкой устраняем этоот глюк
  231.     jump = (speedY < 5 && speedY > 0)? true : jump;
  232.  
  233.     if (!shoot) {
  234.         if (jump) {
  235.             //в позу полёта
  236.             hero.gotoAndStop(3);
  237.         } else {
  238.             if (oldX != hero._x) {
  239.                 //если позиция по Х изменилась - в позу хотьбы
  240.                 hero.gotoAndStop(2);
  241.             } else {
  242.                 //иначе - по стойке смирно
  243.                 hero.gotoAndStop(1);
  244.             }
  245.         }
  246.     }
  247.     oldX = hero._x;
  248. }
  249.  
  250. checkHitPlatform = function(){
  251.     //перебираем все платформы и проверяем пересечение с персонажем с учётом того,
  252.     //в какую сторону он смотрит
  253.     var i = boxes.length;
  254.     while (i--) {
  255.         var curB = boxes[i];
  256.         if (curB.hitTest(hero.p1)) {
  257.             //контакт справа
  258.             if (hero._xscale > 0) {
  259.                 hero._x = curB._x - curB._width / 2 - hhx;
  260.             } else {
  261.                 hero._x = curB._x + curB._width / 2 + hhx;
  262.             }
  263.         } else if (curB.hitTest(hero.p2)) {
  264.             //контакт снизу
  265.             jump = false;
  266.             speedY = 0;
  267.             hero._y = curB._y - curB._height / 2 - hhy;
  268.         } else if (curB.hitTest(hero.p3)) {
  269.             //контакт слева
  270.             if (hero._xscale > 0) {
  271.                 hero._x = curB._x + curB._width / 2 + hhx;
  272.             } else {
  273.                 hero._x = curB._x - curB._width / 2 - hhx;
  274.             }
  275.         } else if (curB.hitTest(hero.p4)) {
  276.             //контакт сверху
  277.             speedY = 0; // как вариант: speedY *= -1;
  278.             hero._y = curB._y + curB._height / 2 + hhy;
  279.         }
  280.     }
  281. }
  282.  
  283. onEnterFrame = function () {
  284.         stepHero();
  285. };
  286.  
  287. -------------------------------------------------------
  288. -------------------------------------------------------
  289. -------------------------------------------------------
  290. -------------------------------------------------------
  291. function rasterizeMovieClip(obj, bdLev) {
  292.  
  293.     var _par = obj._parent;
  294.     var _lev = (bdLev) ? bdLev : _par.getNextHighestDepth();
  295.  
  296.     var bd_mc = _par.createEmptyMovieClip(obj._name + "BD", _lev);
  297.  
  298.     var bd = new flash.display.BitmapData(obj._width, obj._height, true, 0x00000000);
  299.     bd.draw(obj);
  300.  
  301.     bd_mc.attachBitmap(bd,bd_mc.getNextHighestDepth());
  302.     bd_mc._x = obj._x;
  303.     bd_mc._y = obj._y;
  304.  
  305.     obj.swapDepths(_par.getNextHighestDepth());
  306.     obj.removeMovieClip();
  307. }
  308.  
  309. -------------------------------------------------------
  310. -------------------------------------------------------
  311. -------------------------------------------------------
  312. -------------------------------------------------------
  313.  
  314. //переменная таймера для добавления противников на сцену
  315. var spiderCount = 0;
  316. //хранит уровень куда добавляются объекты
  317. var lev = 0;
  318.  
  319. onEnterFrame = function(){
  320.   //функция действия главного героя
  321.     actionHero();
  322.  
  323.     if(spiderCount++ > 50) {
  324.         spiderCount = 0;
  325.         //добавляем паучка
  326.         placeSpider();
  327.     }
  328. }
  329.  
  330. //------------------------------------
  331. var step = 3;
  332. var rotDirSpeed = 6;
  333. var rotToMouseSpeed = 7;
  334.  
  335. function actionHero () {
  336.     if (Key.isDown(Key.LEFT)) {
  337.         hero._rotation -= rotDirSpeed;
  338.     } else if (Key.isDown(Key.RIGHT)) {
  339.         hero._rotation += rotDirSpeed;
  340.     }
  341.  
  342.     var mDx = _xmouse - hero._x;
  343.     var mDy = _ymouse - hero._y;
  344.     //угол поворота между клипом hero и мышкой в градусах
  345.     var mAngleD = Math.atan2(mDy, mDx) / Math.PI * 180;
  346.     //угол поворота между башней и мышкой в градусах
  347.     var dAngleD = hero._rotation + hero.body._rotation - mAngleD;
  348.  
  349.     //без этой проверки башня будет неправильно крутиться
  350.     //при переходе границы -180 и +180 градусов
  351.     if (dAngleD > 180) {
  352.         dAngleD = -360 + dAngleD;
  353.     } else if (dAngleD < -180) {
  354.         dAngleD = 360 + dAngleD;
  355.     }
  356.     //поворачиваем башню с нашей скоростью
  357.     if(Math.abs(dAngleD) < rotToMouseSpeed) {
  358.         hero.body._rotation -= dAngleD;
  359.     } else if(dAngleD > 0) {
  360.         hero.body._rotation -= rotToMouseSpeed;
  361.     } else {
  362.         hero.body._rotation += rotToMouseSpeed;
  363.     }
  364.     //проверка на реализм поворота корпуса человека
  365.     if(hero.body._rotation < -90) {
  366.         hero.body._rotation = -90;
  367.     } else if(hero.body._rotation > 90) {
  368.         hero.body._rotation = 90;
  369.     }
  370.  
  371.     var dirAngle = hero._rotation / 180 * Math.PI;
  372.     if (Key.isDown(Key.UP)) {
  373.         hero.foot.play();
  374.         hero._x += step * Math.cos(dirAngle);
  375.         hero._y += step * Math.sin(dirAngle);
  376.     } else if (Key.isDown(Key.DOWN)) {
  377.         hero.foot.play();
  378.         hero._x -= step * Math.cos(dirAngle);
  379.         hero._y -= step * Math.sin(dirAngle);
  380.     } else {
  381.         hero.foot.stop();
  382.     }
  383.  
  384.     //стреляем если зажата клавиша мышки
  385.     if(Key.isDown(1)){
  386.         hero.body.play();
  387.     }
  388. };
  389.  
  390. //скрываем эталонный клип, все дубликаты при этом будут видимы
  391. blood._visible = false;
  392.  
  393. //дублирует спецэффект и располагает поверх героя
  394. placeBlood = function() {
  395.     lev++;
  396.     var d = blood.duplicateMovieClip("b" + lev, lev + 20000);
  397.     d._x = hero._x;
  398.     d._y = hero._y;
  399. }
  400.  
  401. //------------------------------------
  402. //скорость полёта пули
  403. bulletSpeed = 18;
  404.  
  405. //функция добавляет пулю на сцену, перемещает к дулу пулемёта,
  406. //поворачивает по направлению выстрела и прописывает для неё алгоритм движения
  407. placeBullet = function (tgt) {
  408.     lev++;
  409.  
  410.     //пересчитываем координаты конца дула в координаты текущего клипа
  411.     var p = {x:tgt._x, y:tgt._y};
  412.     tgt._parent.localToGlobal(p);
  413.     globalToLocal(p);
  414.  
  415.     //создаём дубликат клипа с пулей, позиционируем и поворачиваем
  416.     var d = bullet.duplicateMovieClip("b" + lev, lev);
  417.     d._x = p.x;
  418.     d._y = p.y;
  419.     d._rotation = hero._rotation + hero.body._rotation;
  420.     d.a = d._rotation / 180 * Math.PI;
  421.  
  422.     //алгоритм действий пули
  423.     d.onEnterFrame = function() {
  424.         //смещение
  425.         this._x += bulletSpeed * Math.cos(this.a);
  426.         this._y += bulletSpeed * Math.sin(this.a);
  427.  
  428.         //проверка на выход за границы сцены
  429.         if (this._x < ground._x - this._width || this._x > ground._x + ground._width + this._width || this._y < ground._y - this._height || this._y > ground._y + ground._height + this._height) {
  430.             this.removeMovieClip();
  431.         }
  432.  
  433.         //проверка попадания в противников
  434.         //ВНИМАНИЕ: в коде проверяется пересечение клипа текущей пули с ВНУТРЕННИМ клипом hit текущего противника
  435.         var i = spiders.length;
  436.         while (i--) {
  437.             var curS = spiders[i];
  438.             if (curS.hit.hitTest(this)) {
  439.                 this.removeMovieClip();
  440.                 curS.gotoAndStop(2);
  441.                 removeSpider(curS);
  442.             }
  443.         }
  444.     };
  445.  
  446. };
  447.  
  448.  
  449. //------------------------------------
  450. //массив хранит список всех противников которые бегают по сцене в данный момент
  451. var spiders = new Array();
  452.  
  453. //добавляет паука на сцены и задаёт для него поведение
  454. function placeSpider() {
  455.     lev++;
  456.     var d = spider.duplicateMovieClip("z" + lev, lev);
  457.  
  458.     //случайным образом выбираем с какой стороны экрана ему появиться
  459.     if (Math.random() < .5) {
  460.         d._x = ground._x + Math.random() * ground._width;
  461.         if (Math.random() < .5) {
  462.             d._y = ground._y - d._height / 2;
  463.         } else {
  464.             d._y = ground._y + ground._height + d._height / 2;
  465.         }
  466.     } else {
  467.         d._y = ground._y + Math.random() * ground._height;
  468.         if (Math.random() < .5) {
  469.             d._x = ground._x - d._width / 2;
  470.         } else {
  471.             d._x = ground._x + ground._width + d._width / 2;
  472.         }
  473.     }
  474.  
  475.     //первоначальный поворот на цель и определение скорости
  476.     var dx = hero._x - d._x;
  477.     var dy = hero._y - d._y;
  478.     d.a = Math.atan2(dy, dx);
  479.     d._rotation = d.a / Math.PI * 180;
  480.     d.speed = Math.random() * 2 + 2;
  481.  
  482.     //поведение противника
  483.     d.onEnterFrame = function() {
  484.         //смещается туда куда смотрит
  485.         this._x += this.speed * Math.cos(this.a);
  486.         this._y += this.speed * Math.sin(this.a);
  487.  
  488.         //постоянно корректирует своё направление движения на главного героя
  489.         var dx = hero._x - this._x;
  490.         var dy = hero._y - this._y;
  491.         this.a = Math.atan2(dy, dx);
  492.         this._rotation = this.a / Math.PI * 180;
  493.  
  494.         //проверка на достижение цели
  495.         var dist = Math.sqrt(dx * dx + dy * dy);
  496.         if (dist < 25 && !placed) {
  497.             //запустить спецэффект
  498.             placeBlood();
  499.             //запустить клип с сообщением о проигрыше
  500.             //в этом примере не описан, но можете иметь ввиду
  501.             _parent.black.play();
  502.             delete this.onEnterFrame;
  503.         }
  504.     };
  505.     //добавляем новосозданного паука в список
  506.     spiders.push(d);
  507. }
  508.  
  509. //функция удаления паука из списка противников
  510. //вызывается при попадании пули
  511. function removeSpider(s) {
  512.     var i = spiders.length;
  513.     while(i--) {
  514.         var curS = spiders[i];
  515.         if(curS == s) {
  516.             //удаляём поведение, т.к. мёртвые уже ничего не решают
  517.             delete curS.onEnterFrame;
  518.             spiders.splice(i, 1);
  519.         }
  520.     }
  521. }
  522.  
  523. -------------------------------------------------------
  524. -------------------------------------------------------
  525. -------------------------------------------------------
  526. -------------------------------------------------------
  527.  
  528. rotToMouseSpeed = 3;//скорость поворота
  529.  
  530. function onEnterFrame() {
  531.     mDx = _xmouse - body._x;
  532.     mDy = _ymouse - body._y;
  533.     mAngle = Math.atan2(mDy, mDx);
  534.     //получаем угол между мышкой и башней в градусах
  535.     mAngleD = mAngle / Math.PI * 180;
  536.     //сколько градусов нехватает для полного поворота на мышь
  537.     dAngleD = body._rotation - mAngleD;
  538.     //без этой проверки башня будет неправильно крутиться
  539.     //при переходе границы -180 и +180 градусов
  540.     if (dAngleD > 180) {
  541.         dAngleD = -360 + dAngleD;
  542.     } else if (dAngleD < -180) {
  543.         dAngleD = 360 + dAngleD;
  544.     }
  545.     //поворачиваем башню с нашей скоростью
  546.     if(Math.abs(dAngleD) < rotToMouseSpeed) {
  547.         body._rotation -= dAngleD;
  548.     } else if(dAngleD > 0) {
  549.         body._rotation -= rotToMouseSpeed;
  550.     } else {
  551.         body._rotation += rotToMouseSpeed;
  552.     }
  553. }
  554.  
  555. //------------------------------------------------
  556. var step = 2;
  557. var rotDirSpeed = 5;
  558. var rotToMouseSpeed = 7;
  559.  
  560. onEnterFrame = function () {
  561.     if (Key.isDown(Key.LEFT)) {
  562.         hero._rotation -= rotDirSpeed;
  563.     } else if (Key.isDown(Key.RIGHT)) {
  564.         hero._rotation += rotDirSpeed;
  565.     }
  566.  
  567.     var mDx = _xmouse - hero._x;
  568.     var mDy = _ymouse - hero._y;
  569.     //угол поворота между клипом hero и мышкой в градусах
  570.     var mAngleD = Math.atan2(mDy, mDx) / Math.PI * 180;
  571.     //угол поворота между башней и мышкой в градусах
  572.     var dAngleD = hero._rotation + hero.body._rotation - mAngleD;
  573.  
  574.     //без этой проверки башня будет неправильно крутиться
  575.     //при переходе границы -180 и +180 градусов
  576.     if (dAngleD > 180) {
  577.         dAngleD = -360 + dAngleD;
  578.     } else if (dAngleD < -180) {
  579.         dAngleD = 360 + dAngleD;
  580.     }
  581.     //поворачиваем башню с нашей скоростью
  582.     if(Math.abs(dAngleD) < rotToMouseSpeed) {
  583.         hero.body._rotation -= dAngleD;
  584.     } else if(dAngleD > 0) {
  585.         hero.body._rotation -= rotToMouseSpeed;
  586.     } else {
  587.         hero.body._rotation += rotToMouseSpeed;
  588.     }
  589.     //проверка на реализм поворота корпуса человека
  590.     if(hero.body._rotation < -90) {
  591.         hero.body._rotation = -90;
  592.     } else if(hero.body._rotation > 90) {
  593.         hero.body._rotation = 90;
  594.     }
  595.  
  596.     var dirAngle = hero._rotation / 180 * Math.PI;
  597.     if (Key.isDown(Key.UP)) {
  598.         hero.foot.play();
  599.         hero._x += step * Math.cos(dirAngle);
  600.         hero._y += step * Math.sin(dirAngle);
  601.     } else if (Key.isDown(Key.DOWN)) {
  602.         hero.foot.play();
  603.         hero._x -= step * Math.cos(dirAngle);
  604.         hero._y -= step * Math.sin(dirAngle);
  605.     } else {
  606.         hero.foot.stop();
  607.     }
  608. };
  609. onMouseDown = function () {
  610.     hero.body.play();
  611. };
  612.  
  613. -------------------------------------------------------
  614. -------------------------------------------------------
  615. -------------------------------------------------------
  616. -------------------------------------------------------
  617. import flash.display.BitmapData;
  618.  
  619. step = 2;
  620.  
  621. //переводим зону проходимости в пиксельный вид
  622. var pathBD = new BitmapData(path._width, path._height, false, 0x000000);
  623. pathBD.draw(path);
  624.  
  625. path._visible = false;
  626.  
  627. onEnterFrame = function () {
  628.     var dx = _xmouse - man._x;
  629.     var dy = _ymouse - man._y;
  630.     var angle = Math.atan2(dy, dx);
  631.     var dist = Math.sqrt(dx * dx + dy * dy);
  632.     if (dist > step) {
  633.         tgtX = man._x + step * Math.cos(angle);
  634.         tgtY = man._y + step * Math.sin(angle);
  635.  
  636.         //Если цвет пиксела черный, значит препятствие
  637.         if (pathBD.getPixel(tgtX, tgtY) == 0) {
  638.             var dAngle = dAngleRadian(direction, angle);
  639.             workAngle = angle + dAngle * .8;
  640.             var outFlag = false;
  641.             for (var i = 0; i < 360 && !outFlag; i += 15) {
  642.                 for (var j = -1; j <= 1; j += 2) {
  643.                     var a = workAngle + radian(i) * j;
  644.                     var tempX = man._x + step * Math.cos(a);
  645.                     var tempY = man._y + step * Math.sin(a);
  646.                     if (pathBD.getPixel(tempX, tempY) != 0) {
  647.                         tgtX = tempX;
  648.                         tgtY = tempY;
  649.                         break;
  650.                     }
  651.                 }
  652.             }
  653.         }
  654.         var timeDx = tgtX - man._x;
  655.         var timeDy = tgtY - man._y;
  656.         direction = Math.atan2(timeDy, timeDx);
  657.         var dAngle = dAngleDegree(direction * 180 / Math.PI, man._rotation);
  658.         man._rotation += dAngle * .2;
  659.         man._x = tgtX;
  660.         man._y = tgtY;
  661.         play();
  662.     } else {
  663.         gotoAndStop(5);
  664.     }
  665. };
  666.  
  667. function dAngleRadian (a1, a2) {
  668.     var da = a1 - a2;
  669.     if (da > Math.PI) {
  670.         da = -Math.PI * 2 + da;
  671.     } else if (da < -Math.PI) {
  672.         da = Math.PI * 2 + da;
  673.     }
  674.     return da;
  675. };
  676. function dAngleDegree(a1, a2) {
  677.     var da = a1 - a2;
  678.     if (da > 180) {
  679.         da = -360 + da;
  680.     } else if (da < -180) {
  681.         da = 360 + da;
  682.     }
  683.     return da;
  684. };
  685. function degree(a) {
  686.     return a / Math.PI * 180;
  687. };
  688. function radian(a) {
  689.     return a / 180 * Math.PI;
  690. };
  691.  
  692. -------------------------------------------------------
  693. -------------------------------------------------------
  694. -------------------------------------------------------
  695. -------------------------------------------------------
  696.  
  697. //Шаг за 1 кадр
  698. step = 2;
  699.  
  700. onEnterFrame = function(){
  701.     var dx = _root._xmouse - man._x;
  702.     var dy = _root._ymouse - man._y;
  703.     if (Math.abs(dx) > step) {
  704.         var tgtX = man._x + ((dx > 0)? step : -step);
  705.     }
  706.     if (Math.abs(dy) > step) {
  707.         var tgtY = man._y + ((dy > 0)? step : -step);
  708.     }
  709.  
  710.     //Запоминаем положение
  711.     oldX = man._x;
  712.     oldY = man._y;
  713.  
  714.     //Смещаемся если новые координаты попадают в зону
  715.     if (path.hitTest(man._x, tgtY, true)) {
  716.         man._y = tgtY;
  717.     }
  718.     if(path.hitTest(tgtX, man._y, true)) {
  719.         man._x = tgtX;
  720.     }
  721.  
  722.     timeDx = man._x - oldX;
  723.     timeDy = man._y - oldY;
  724.     if(timeDx==0 && timeDy==0) {
  725.         //Если не было смещения - в кадр где стоим
  726.         man.gotoAndStop(5);
  727.     }else {
  728.         man.play();
  729.         //Поворачиваемся по ходу движения
  730.         rot = Math.atan2(timeDy, timeDx)*180/Math.PI;
  731.         man._rotation = rot;
  732.     }
  733.  
  734. }
  735.  
  736. //-----------------------------------------------------
  737.  
  738. step = 2;
  739.  
  740. onEnterFrame = function(){
  741.     var dx = _xmouse - man._x;
  742.     var dy = _ymouse - man._y;
  743.     var angle = Math.atan2(dy, dx);
  744.     var dist = Math.sqrt(dx*dx + dy*dy);
  745.     if(dist > step) {
  746.         tgtX = man._x + step * Math.cos(angle);
  747.         tgtY = man._y + step * Math.sin(angle);
  748.         man._rotation = angle*180/Math.PI;
  749.         if (path.hitTest(tgtX, tgtY, true)) {
  750.             man._x = tgtX;
  751.             man._y = tgtY;
  752.             man.play();
  753.         } else {
  754.             man.gotoAndStop(5);
  755.         }
  756.  
  757.     }
  758. }
  759.  
  760. //-----------------------------------------------------
  761. step = 2;
  762.  
  763. onEnterFrame = function(){
  764.     var dx = _xmouse - man._x;
  765.     var dy = _ymouse - man._y;
  766.     //Направление (угол) к цели
  767.     var angle = Math.atan2(dy, dx);
  768.     var dist = Math.sqrt(dx*dx + dy*dy);
  769.     if(dist > step) {
  770.         //пробуем пройти напролом
  771.         tgtX = man._x + step * Math.cos(angle);
  772.         tgtY = man._y + step * Math.sin(angle);
  773.         if (!path.hitTest(tgtX, tgtY, true)){
  774.             //напролом не получилось, вычисляем базовое направление
  775.             var dAngle = dAngleRadian(direction, angle);
  776.             workAngle = angle + dAngle*.8;
  777.             //Шаг поворота - 10 градусов
  778.             for(var i = 0; i < 360; i += 10) {
  779.                 for(var j = -1; j <= 1; j += 2) {
  780.                     var a = workAngle + radian(i) * j;
  781.                     var tempX = man._x + step * Math.cos(a);
  782.                     var tempY = man._y + step * Math.sin(a);
  783.                     if (path.hitTest(tempX, tempY, true)) {
  784.                         //точка выхода найдена. Запоминаем ее и прерываем цикл
  785.                         tgtX = tempX;
  786.                         tgtY = tempY;
  787.                         break;
  788.                     }
  789.                 }
  790.             }
  791.         }
  792.         var timeDx = tgtX - man._x;
  793.         var timeDy = tgtY - man._y;
  794.         //направление движения
  795.         direction = Math.atan2(timeDy, timeDx);
  796.         var dAngle = dAngleDegree(direction*180/Math.PI, man._rotation);
  797.         //поворячиваем клип к направлени движения на 5-ю часть
  798.         man._rotation += dAngle * .2;
  799.         man._x = tgtX;
  800.         man._y = tgtY;
  801.         man.play();
  802.     } else {
  803.         //стоим
  804.         man.gotoAndStop(5);
  805.     }
  806. }
  807.  
  808. function dAngleRadian(a1, a2) {
  809.     var da = a1 - a2;
  810.     if (da > Math.PI) {
  811.         da = -Math.PI*2 + da;
  812.     } else if (da < -Math.PI) {
  813.         da = Math.PI*2 + da;
  814.     }
  815.     return da;
  816. }
  817. function dAngleDegree(a1, a2) {
  818.     var da = a1 - a2;
  819.     if (da > 180) {
  820.         da = -360 + da;
  821.     } else if (da < -180) {
  822.         da = 360 + da;
  823.     }
  824.     return da;
  825. }
  826. function degree(a) {
  827.     return a / Math.PI * 180;
  828. }
  829. function radian(a) {
  830.     return a / 180 * Math.PI;
  831. }
  832.  
  833. -------------------------------------------------------
  834. -------------------------------------------------------
  835. -------------------------------------------------------
  836. -------------------------------------------------------
  837.  
  838. lev = 0;
  839. gravity = 1;//величина гравитации подбирается (визуально зависит от frameRate)
  840. function placeTarget() {
  841.     lev++;
  842.     var d = target.duplicateMovieClip("t" + lev, lev);
  843.     d.speedY = -15 - Math.random() * 5;//начальные значения скорости
  844.     d.speedX = Math.random() * 4;// плюс небольшой разброс
  845.     d.rotSpeed = (Math.random() - .5) * 20;//случайный шаг для вращения
  846.     if (Math.random() < .5) {
  847.         d.speedX = -d.speedX;//больше разницы - отражаем бутылку по горизонтали
  848.     }
  849.     d.onEnterFrame = function() {
  850.         this.speedY += gravity;
  851.         this._y += this.speedY;
  852.         this._x += this.speedX;
  853.         this._rotation += this.rotSpeed;
  854.         if (this._y > target._y) {
  855.             this.removeMovieClip();//удаляем если улетела ниже экрана
  856.         }
  857.     };
  858. }
  859. count = 0;
  860. onEnterFrame = function () {
  861.     if (count++ > 15) {//добавляем бутылку каждый 15-й кадр
  862.         count = 0;
  863.         placeTarget();
  864.     }
  865. };
  866.  
  867. //--------------------------------------------------------
  868. score = 0;
  869. all = [];//тут хранятся все летающие объекты
  870. lev = 0;
  871. gravity = 1;
  872. pos = 0;
  873. neg = 0;
  874. count = 0;
  875. crash._visible = false;
  876.  
  877. cursor.swapDepths(12002432);//прицел выше всех бутылок
  878. Mouse.hide();
  879.  
  880. function placeTarget() {
  881.     lev++;
  882.     var d = target.duplicateMovieClip("t" + lev, lev);
  883.     d.speedY = -15 - Math.random() * 5;
  884.     d.speedX = Math.random() * 4;
  885.     d.rotSpeed = (Math.random() - .5) * 20;
  886.     d._x = box._x + Math.random() * box._width;
  887.     if (Math.random() < .5) {
  888.         d.speedX = -d.speedX;
  889.     }
  890.     if ((Math.random() < .5 && pos < 1) || neg >= 5) {
  891.         d.gotoAndStop(1);
  892.         pos++;
  893.         neg = 0;
  894.     } else {
  895.         d.gotoAndStop(2);
  896.         var t = Math.random();
  897.         if(t < .33) {
  898.             d.obj.gotoAndStop(1);
  899.         } else if(t < .66) {
  900.             d.obj.gotoAndStop(2);
  901.         } else{
  902.             d.obj.gotoAndStop(3);
  903.         }
  904.         neg++;
  905.         pos = 0;
  906.     }
  907.     d.onEnterFrame = function() {
  908.         this.speedY += gravity;
  909.         this._y += this.speedY;
  910.         this._x += this.speedX;
  911.         this._rotation += this.rotSpeed;
  912.         if (this._y > box._y) {
  913.             removeObj(this);
  914.             this.removeMovieClip();
  915.         }
  916.     };
  917.     all.push(d);
  918. }
  919. function removeObj(obj){
  920.     var i = all.length;
  921.     while(i--) {
  922.         if(all[i] == obj) {
  923.             all.splice(i, 1);
  924.         }
  925.     }
  926. }
  927. function placeCrash(x, y, _t) {
  928.     lev++;
  929.     var d = crash.duplicateMovieClip("c" + lev, lev);
  930.     d.type = _t;
  931.     d._x = x;
  932.     d._y = y;
  933. }
  934. onEnterFrame = function () {
  935.     if (count++ > 15) {
  936.         count = 0;
  937.         placeTarget();
  938.     }
  939.     cursor._x = _xmouse;
  940.     cursor._y = _ymouse;
  941. };
  942.  
  943. onMouseDown = function(){
  944.     cursor.play();//анимация выстрела
  945.     var i = all.length;
  946.     while(i--) {
  947.         var curT = all[i];
  948.         if(curT.hitTest(_root._xmouse, _root._ymouse, true)) {
  949.             if(curT._currentframe == 1) {
  950.                 var type = 1;
  951.             } else{
  952.                 var type = curT.obj._currentframe + 1;
  953.             }
  954.             placeCrash(curT._x, curT._y, type);
  955.             if(curT._currentframe == 2) {
  956.                 score += 20;
  957.                 if(score >= 100) {
  958.                     trace("Вы победили");
  959.                 }
  960.             }else {
  961.                 score -= 25;
  962.                 score = (score < 0)? 0 : score;
  963.             }
  964.             curT.removeMovieClip();
  965.             all.splice(i, 1);
  966.         }
  967.     }
  968. }
  969.  
  970. -------------------------------------------------------
  971. -------------------------------------------------------
  972. -------------------------------------------------------
  973. -------------------------------------------------------
  974. WIDTH = zone._width;
  975. HEIGHT = zone._height;
  976. LEFT = zone._x;
  977. TOP = zone._y;
  978. RIGHT = LEFT + WIDTH;
  979. BOTTOM = TOP + HEIGHT;
  980.  
  981. speed = 0;
  982. speedLimit = 8;
  983. speedStep = .5;
  984. rotLimit = 35;
  985. rotStep = 3;
  986. trailerRotLimit = 55 / 180 * Math.PI;
  987.  
  988. processKey = function () {
  989.     if (Key.isDown(Key.CONTROL) || Key.isDown(Key.SPACE)) {
  990.         car.kovsh.play();
  991.     }
  992.     if (Key.isDown(Key.LEFT)) {
  993.         if (car.left._rotation > -rotLimit) {
  994.             car.left._rotation = car.right._rotation -= rotStep;
  995.         }
  996.     } else if (Key.isDown(Key.RIGHT)) {
  997.         if (car.left._rotation < rotLimit) {
  998.             car.left._rotation = car.right._rotation += rotStep;
  999.         }
  1000.     }
  1001.     if (Key.isDown(Key.UP)) {
  1002.         speed += (speed < speedLimit)? speedStep : 0;
  1003.     } else if (Key.isDown(Key.DOWN)) {
  1004.         speed += (speed > -speedLimit)? -speedStep : 0;
  1005.     } else {
  1006.         speed += (speed < 0)? speedStep : (speed > 0)? -speedStep : 0;
  1007.     }
  1008. };
  1009. checkCycle = function () {
  1010.     bounds = car.getBounds(this);
  1011.     boundWidth = bounds.xMax - bounds.xMin;
  1012.     boundHeight = bounds.yMax - bounds.yMin
  1013.     if(bounds.xMax < LEFT) {
  1014.         car._x = RIGHT + car._x - bounds.xMin;
  1015.     } else if(bounds.xMin > RIGHT) {
  1016.         car._x = LEFT - (bounds.xMax - car._x);
  1017.     }
  1018.     if(bounds.yMax < TOP) {
  1019.         car._y = BOTTOM + (car._y - bounds.yMin);
  1020.     } else if(bounds.yMin > BOTTOM) {
  1021.         car._y = TOP - (bounds.yMax - car._y);
  1022.     }
  1023. };
  1024. function move(){
  1025.     if(Math.abs(speed) > 0) {
  1026.         car._rotation += car.left._rotation * speed / car.left._x;
  1027.     }
  1028.     angle = car._rotation * Math.PI / 180;
  1029.     speedX = speed * Math.cos(angle);
  1030.     speedY = speed * Math.sin(angle);
  1031.     car._x += speedX;
  1032.     car._y += speedY;
  1033. }
  1034.  
  1035. function correctTrailer(slave, master){
  1036.     if(speed){
  1037.         //Пересчитываем точку в родительскую систему координат
  1038.         var masterDot = {x:master.dotOut._x, y:master.dotOut._y};
  1039.         master.localToGlobal(masterDot);
  1040.         globalToLocal(masterDot);
  1041.  
  1042.         var dx = masterDot.x - slave._x;
  1043.         var dy = masterDot.y - slave._y;
  1044.  
  1045.         //Угол между прицепом и машиной
  1046.         var aRad = Math.atan2(dy, dx);
  1047.  
  1048.         //Угол поворота самой машины
  1049.         var masterRotRad = master._rotation / 180 * Math.PI;
  1050.  
  1051.         //Разница между ними
  1052.         var dAngle = masterRotRad - aRad;
  1053.  
  1054.         //Коррекция перехода 180/-180 градусов
  1055.         if (dAngle > Math.PI) {
  1056.             dAngle = -Math.PI*2 + dAngle;
  1057.         } else if (dAngle < -Math.PI) {
  1058.             dAngle = Math.PI*2 + dAngle;
  1059.         }
  1060.         if(speed < 0) {
  1061.             //Выполняется только при движении назад
  1062.             //Ограничение на поворот и торможение из-за прицепа
  1063.             if(dAngle >= trailerRotLimit) {
  1064.                 aRad = masterRotRad - trailerRotLimit;
  1065.                 speed *= .8;
  1066.             } else if(dAngle <= -trailerRotLimit) {
  1067.                 aRad = masterRotRad + trailerRotLimit;
  1068.                 speed *= .8;
  1069.             }
  1070.  
  1071.             //Обратная связь на машину в результате торможения
  1072.             //Коэффициенты .5 и 3 подбираются вручную
  1073.             if(dAngle >= trailerRotLimit * .5) {
  1074.                 master._rotation += speed / speedLimit * 3;
  1075.             } else if(dAngle <= -trailerRotLimit * .5) {
  1076.                 master._rotation -= speed / speedLimit * 3;
  1077.             }
  1078.         }
  1079.  
  1080.         //Убираем паразитную скорость (погрешность округления чисел)
  1081.         if(Math.abs(speed) < speedStep && !Key.isDown(Key.DOWN)) {
  1082.             speed = 0;
  1083.         }
  1084.  
  1085.         //Поворачиваем прицеп к машине
  1086.         var a = aRad / Math.PI * 180;
  1087.         slave._rotation = a;
  1088.  
  1089.         //Пододвигаем прицеп чтобы была стыковка
  1090.         slave._x = masterDot.x - Math.cos(aRad) * slave.dotIn._x;
  1091.         slave._y = masterDot.y - Math.sin(aRad) * slave.dotIn._x;
  1092.     }
  1093. }
  1094. onEnterFrame = function() {
  1095.     processKey();
  1096.     move();
  1097.     checkCycle();
  1098.     correctTrailer(trailer, car);
  1099. }
  1100.  
  1101. -------------------------------------------------------
  1102. -------------------------------------------------------
  1103. -------------------------------------------------------
  1104. -------------------------------------------------------
  1105. lev = 0;
  1106. speedY = 5;
  1107. dot._visible = false;//скрываем оригинал
  1108. placeDot = function() {
  1109.     lev++;
  1110.     d = dot.duplicateMovieClip("d" + lev, lev);
  1111.     d._x = Math.random()* 40 - 20;//случайное положение - разброс
  1112.     d._y = Math.random()* 16 - 8;
  1113.     d._xscale = d._yscale = 50 + Math.random() * 50;
  1114.     d.onEnterFrame = function() {
  1115.         this._y -= speedY;
  1116.         this._xscale = this._yscale *= .96;
  1117.         if(this._xscale < 2) {
  1118.             this.removeMovieClip();
  1119.         }
  1120.     }
  1121. }
  1122. onEnterFrame = placeDot;
  1123.  
  1124. //-----------------------------------------------
  1125. dot._visible = false;
  1126. lev = 0;
  1127. placeDot = function() {
  1128.     lev++;
  1129.     var d = dot.duplicateMovieClip("b" + lev, lev);
  1130.     d.speed = 1 + Math.random() * .5;//скорость
  1131.     d.a = 1 + Math.random() * 1;//амплитуда качания по _x
  1132.     d.s = .001 + Math.random() * .08;//скорость качания
  1133.     d.t = Math.random() * 10;//случайное начальное положение для синуса
  1134.     d.y0 = d._y += Math.random() * 2 - 1;//разброс по _y
  1135.     d.x0 = d._x += Math.random() * 2 - 1;//разброс по _x
  1136.     d._xscale = d._yscale = 50 + Math.random() * 50;//случайный размер
  1137.     d.onEnterFrame = function() {
  1138.         this._y -= this.speed;
  1139.         this.a += this.s;//амплитуда немного увеличивается со временем
  1140.         this._x = this.x0 + this.a * Math.sin(this.t += this.s);
  1141.         this._xscale = this._yscale *= .99;//а размер немного уменьшается (хуже видно)
  1142.         if(this._xscale < 2) {
  1143.             this.removeMovieClip();
  1144.         }
  1145.     }
  1146. }
  1147. onEnterFrame = placeDot;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement