Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- // Create a number of trees randomly
- // positioned within the document
- function createTrees(numberOfTrees:int):void {
- // variable to store trees created
- // in the loop - the DisplayObject
- // type satisfies both MovieClip
- // and Bitmap instances
- var currTree:DisplayObject;
- // loop through the number of trees
- while(numberOfTrees--){
- // randomly add a tree either
- // as a bitmap or a movie clip
- if (Math.random() < .5) {
- // create a new Tree instance
- // Tree is the class name given to
- // the tree symbol in the library
- currTree = new Tree();
- }else{
- // create the tree BitmapData instance
- // from the library, then add it to a
- // new Bitmap instance
- var currTreeData:TreeImageData = new TreeImageData(0, 0);
- currTree = new Bitmap(currTreeData);
- }
- // position the new instance randomly on
- // the screen based on the stage's size.
- // subtracting the tree size from the stage
- // size keeps the trees on screen
- currTree.x = Math.random() * (stage.stageWidth - currTree.width);
- currTree.y = Math.random() * (stage.stageHeight - currTree.height);
- // don't forget to add the tree
- // to the display list
- addChild(currTree);
- }
- }
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- // Arrange all children in the specified
- // container based on their y value
- function sortChildrenByY(container:MovieClip):void {
- var i:int;
- var childList:Array = new Array();
- // first put all children in an array
- i = container.numChildren;
- while(i--){
- childList[i] = container.getChildAt(i);
- }
- // next, sort the array based on the
- // elements' y property
- childList.sortOn("y", Array.NUMERIC);
- // now match the arrangement of the array
- // with the arrangement of the display list
- i = container.numChildren;
- while(i--){
- // if the child at position i in the array
- // does not match the child at position
- // i in the display list, set that child
- // to the i position in the display list
- if (childList[i] != container.getChildAt(i)){
- container.setChildIndex(childList[i], i);
- }
- }
- }
- / Create an instance of a library bitmap
- // given the Class name of MyImage
- var imageData:MyImage = new MyImage(0, 0);
- // Give the instance to a Bitmap through its
- // constructor, then add it to the display list
- var imageBmp:Bitmap = new Bitmap(imageData);
- addChild(imageBmp);
- // Add movie clip from the library to display list
- var myMovie:CustomMovieClass = new CustomMovieClass();
- addChild(myMovie);
- // Remove movie clip from the library from display list
- removeChild(myMovie);
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- particle._visible = false;
- for (z = 0; z < 200; z++) {
- var dupe = particle.duplicateMovieClip("s" + z, z);
- dupe._x = Math.random() * 550;
- dupe._y = Math.random() * 200;
- dupe._xscale = dupe._yscale = Math.random() * 50 + 50;
- dupe._rotation = Math.random() * 360;
- dupe._alpha = Math.random() * 100;
- }
- //------------------------------------
- function _fill(obj) {
- obj._x = Math.random() * 550;
- obj._y = Math.random() * 200;
- obj._xscale = obj._yscale = Math.random() * 50 + 50;
- obj._rotation = Math.random() * 360;
- obj._alpha = Math.random() * 100;
- }
- //------------------------------------
- // заполняем первый этаж "мусором"
- for (z = 1; z < 200; z++) {
- var tmp = bg.particle.duplicateMovieClip("s" + z, z);
- _fill(tmp);
- tmp.gotoAndStop(Math.round(Math.random() * 2) + 1);
- }
- // второй этаж - травой
- for (z = 201; z < 400; z++) {
- var tmp = bg.particle.duplicateMovieClip("s" + z, z);
- _fill(tmp);
- tmp.gotoAndStop(Math.round(Math.random() * 2) + 4);
- }
- // третий этаж ромашками
- for (z = 401; z < 500; z++) {
- var tmp = bg.particle.duplicateMovieClip("s" + z, z);
- _fill(tmp);
- tmp.gotoAndStop(6);
- }
- var tmp_bitmap = new flash.display.BitmapData(550, 200, false, 0x00000000);
- bg_rastr1 = this.createEmptyMovieClip("bg2", 10000);
- bg_rastr2 = this.createEmptyMovieClip("bg3", 10001);
- tmp_bitmap.draw(bg);
- bg_rastr1.attachBitmap(tmp_bitmap,10002);
- bg_rastr2.attachBitmap(tmp_bitmap,1003);
- bg_rastr2._xscale = 400;
- bg_rastr2._yscale = 400;
- //маскируем увеличенную копию
- bg_rastr2.setMask(this._mask);
- //И удаляем оригинал с векторным изображением нашего фона
- bg.swapDepths(10004);
- bg.removeMovieClip();
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- //массив с платформами
- var boxes = [];
- //каждая платформа при старте вызывает эту функцию и передаёт себя как параметр
- addBox = function (obj) {
- boxes.push(obj);
- }
- //--------------------------------
- //сила гравитации
- var grav = 1;
- //начальная скорость прыжка
- var jumpSpeed = -11.9;
- //шаг по Х
- var speedX = 5;
- //шаг по Y
- var speedY = 0;
- //максимальная скорость падения
- var maxSpeedY = 14;
- //половина ширины персонажа
- var hhx = (hero.p1._x - hero.p3._x + hero.p1._width / 2 + hero.p3._width / 2) / 2;
- //половина высоты персонажа
- var hhy = (hero.p2._y - hero.p4._y + hero.p2._height / 2 + hero.p4._height / 2) / 2;
- //отображает состояние прыжка
- var jump = false;
- //отображает состояние удара
- var shoot = false;
- Key.addListener(this);
- onKeyDown = function () {
- //прыгаем
- if (Key.isDown(Key.UP) && !jump && !shoot) {
- jump = true;
- speedY = jumpSpeed;
- }
- //бъём
- if (Key.isDown(Key.SPACE) && !jump && !shoot) {
- shoot = true;
- hero.gotoAndStop(1);
- hero.man.body.gotoAndPlay(2);
- }
- };
- function stepHero() {
- if (!shoot) {
- //смещаемся влево/вправо
- if (Key.isDown(Key.LEFT)) {
- hero._xscale = -100;
- hero._x -= (jump) ? speedX * .8 : speedX;
- } else if (Key.isDown(Key.RIGHT)) {
- hero._xscale = 100;
- hero._x += (jump) ? speedX * .8 : speedX;
- }
- }
- //применяем по цепочке: гравитация -> скорость -> _y
- speedY += grav;
- speedY = (speedY > maxSpeedY) ? maxSpeedY : speedY;
- hero._y += speedY;
- //проверка на пересечение с платформами
- checkHitPlatform();
- //если закомментировать строку ниже, то можно будет свалиться с платформы
- //и прыгнуть оттолкнувшись от воздуха. Этой строкой устраняем этоот глюк
- jump = (speedY < 5 && speedY > 0)? true : jump;
- if (!shoot) {
- if (jump) {
- //в позу полёта
- hero.gotoAndStop(3);
- } else {
- if (oldX != hero._x) {
- //если позиция по Х изменилась - в позу хотьбы
- hero.gotoAndStop(2);
- } else {
- //иначе - по стойке смирно
- hero.gotoAndStop(1);
- }
- }
- }
- oldX = hero._x;
- }
- checkHitPlatform = function(){
- //перебираем все платформы и проверяем пересечение с персонажем с учётом того,
- //в какую сторону он смотрит
- var i = boxes.length;
- while (i--) {
- var curB = boxes[i];
- if (curB.hitTest(hero.p1)) {
- //контакт справа
- if (hero._xscale > 0) {
- hero._x = curB._x - curB._width / 2 - hhx;
- } else {
- hero._x = curB._x + curB._width / 2 + hhx;
- }
- } else if (curB.hitTest(hero.p2)) {
- //контакт снизу
- jump = false;
- speedY = 0;
- hero._y = curB._y - curB._height / 2 - hhy;
- } else if (curB.hitTest(hero.p3)) {
- //контакт слева
- if (hero._xscale > 0) {
- hero._x = curB._x + curB._width / 2 + hhx;
- } else {
- hero._x = curB._x - curB._width / 2 - hhx;
- }
- } else if (curB.hitTest(hero.p4)) {
- //контакт сверху
- speedY = 0; // как вариант: speedY *= -1;
- hero._y = curB._y + curB._height / 2 + hhy;
- }
- }
- }
- onEnterFrame = function () {
- stepHero();
- };
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- function rasterizeMovieClip(obj, bdLev) {
- var _par = obj._parent;
- var _lev = (bdLev) ? bdLev : _par.getNextHighestDepth();
- var bd_mc = _par.createEmptyMovieClip(obj._name + "BD", _lev);
- var bd = new flash.display.BitmapData(obj._width, obj._height, true, 0x00000000);
- bd.draw(obj);
- bd_mc.attachBitmap(bd,bd_mc.getNextHighestDepth());
- bd_mc._x = obj._x;
- bd_mc._y = obj._y;
- obj.swapDepths(_par.getNextHighestDepth());
- obj.removeMovieClip();
- }
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- //переменная таймера для добавления противников на сцену
- var spiderCount = 0;
- //хранит уровень куда добавляются объекты
- var lev = 0;
- onEnterFrame = function(){
- //функция действия главного героя
- actionHero();
- if(spiderCount++ > 50) {
- spiderCount = 0;
- //добавляем паучка
- placeSpider();
- }
- }
- //------------------------------------
- var step = 3;
- var rotDirSpeed = 6;
- var rotToMouseSpeed = 7;
- function actionHero () {
- if (Key.isDown(Key.LEFT)) {
- hero._rotation -= rotDirSpeed;
- } else if (Key.isDown(Key.RIGHT)) {
- hero._rotation += rotDirSpeed;
- }
- var mDx = _xmouse - hero._x;
- var mDy = _ymouse - hero._y;
- //угол поворота между клипом hero и мышкой в градусах
- var mAngleD = Math.atan2(mDy, mDx) / Math.PI * 180;
- //угол поворота между башней и мышкой в градусах
- var dAngleD = hero._rotation + hero.body._rotation - mAngleD;
- //без этой проверки башня будет неправильно крутиться
- //при переходе границы -180 и +180 градусов
- if (dAngleD > 180) {
- dAngleD = -360 + dAngleD;
- } else if (dAngleD < -180) {
- dAngleD = 360 + dAngleD;
- }
- //поворачиваем башню с нашей скоростью
- if(Math.abs(dAngleD) < rotToMouseSpeed) {
- hero.body._rotation -= dAngleD;
- } else if(dAngleD > 0) {
- hero.body._rotation -= rotToMouseSpeed;
- } else {
- hero.body._rotation += rotToMouseSpeed;
- }
- //проверка на реализм поворота корпуса человека
- if(hero.body._rotation < -90) {
- hero.body._rotation = -90;
- } else if(hero.body._rotation > 90) {
- hero.body._rotation = 90;
- }
- var dirAngle = hero._rotation / 180 * Math.PI;
- if (Key.isDown(Key.UP)) {
- hero.foot.play();
- hero._x += step * Math.cos(dirAngle);
- hero._y += step * Math.sin(dirAngle);
- } else if (Key.isDown(Key.DOWN)) {
- hero.foot.play();
- hero._x -= step * Math.cos(dirAngle);
- hero._y -= step * Math.sin(dirAngle);
- } else {
- hero.foot.stop();
- }
- //стреляем если зажата клавиша мышки
- if(Key.isDown(1)){
- hero.body.play();
- }
- };
- //скрываем эталонный клип, все дубликаты при этом будут видимы
- blood._visible = false;
- //дублирует спецэффект и располагает поверх героя
- placeBlood = function() {
- lev++;
- var d = blood.duplicateMovieClip("b" + lev, lev + 20000);
- d._x = hero._x;
- d._y = hero._y;
- }
- //------------------------------------
- //скорость полёта пули
- bulletSpeed = 18;
- //функция добавляет пулю на сцену, перемещает к дулу пулемёта,
- //поворачивает по направлению выстрела и прописывает для неё алгоритм движения
- placeBullet = function (tgt) {
- lev++;
- //пересчитываем координаты конца дула в координаты текущего клипа
- var p = {x:tgt._x, y:tgt._y};
- tgt._parent.localToGlobal(p);
- globalToLocal(p);
- //создаём дубликат клипа с пулей, позиционируем и поворачиваем
- var d = bullet.duplicateMovieClip("b" + lev, lev);
- d._x = p.x;
- d._y = p.y;
- d._rotation = hero._rotation + hero.body._rotation;
- d.a = d._rotation / 180 * Math.PI;
- //алгоритм действий пули
- d.onEnterFrame = function() {
- //смещение
- this._x += bulletSpeed * Math.cos(this.a);
- this._y += bulletSpeed * Math.sin(this.a);
- //проверка на выход за границы сцены
- 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) {
- this.removeMovieClip();
- }
- //проверка попадания в противников
- //ВНИМАНИЕ: в коде проверяется пересечение клипа текущей пули с ВНУТРЕННИМ клипом hit текущего противника
- var i = spiders.length;
- while (i--) {
- var curS = spiders[i];
- if (curS.hit.hitTest(this)) {
- this.removeMovieClip();
- curS.gotoAndStop(2);
- removeSpider(curS);
- }
- }
- };
- };
- //------------------------------------
- //массив хранит список всех противников которые бегают по сцене в данный момент
- var spiders = new Array();
- //добавляет паука на сцены и задаёт для него поведение
- function placeSpider() {
- lev++;
- var d = spider.duplicateMovieClip("z" + lev, lev);
- //случайным образом выбираем с какой стороны экрана ему появиться
- if (Math.random() < .5) {
- d._x = ground._x + Math.random() * ground._width;
- if (Math.random() < .5) {
- d._y = ground._y - d._height / 2;
- } else {
- d._y = ground._y + ground._height + d._height / 2;
- }
- } else {
- d._y = ground._y + Math.random() * ground._height;
- if (Math.random() < .5) {
- d._x = ground._x - d._width / 2;
- } else {
- d._x = ground._x + ground._width + d._width / 2;
- }
- }
- //первоначальный поворот на цель и определение скорости
- var dx = hero._x - d._x;
- var dy = hero._y - d._y;
- d.a = Math.atan2(dy, dx);
- d._rotation = d.a / Math.PI * 180;
- d.speed = Math.random() * 2 + 2;
- //поведение противника
- d.onEnterFrame = function() {
- //смещается туда куда смотрит
- this._x += this.speed * Math.cos(this.a);
- this._y += this.speed * Math.sin(this.a);
- //постоянно корректирует своё направление движения на главного героя
- var dx = hero._x - this._x;
- var dy = hero._y - this._y;
- this.a = Math.atan2(dy, dx);
- this._rotation = this.a / Math.PI * 180;
- //проверка на достижение цели
- var dist = Math.sqrt(dx * dx + dy * dy);
- if (dist < 25 && !placed) {
- //запустить спецэффект
- placeBlood();
- //запустить клип с сообщением о проигрыше
- //в этом примере не описан, но можете иметь ввиду
- _parent.black.play();
- delete this.onEnterFrame;
- }
- };
- //добавляем новосозданного паука в список
- spiders.push(d);
- }
- //функция удаления паука из списка противников
- //вызывается при попадании пули
- function removeSpider(s) {
- var i = spiders.length;
- while(i--) {
- var curS = spiders[i];
- if(curS == s) {
- //удаляём поведение, т.к. мёртвые уже ничего не решают
- delete curS.onEnterFrame;
- spiders.splice(i, 1);
- }
- }
- }
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- rotToMouseSpeed = 3;//скорость поворота
- function onEnterFrame() {
- mDx = _xmouse - body._x;
- mDy = _ymouse - body._y;
- mAngle = Math.atan2(mDy, mDx);
- //получаем угол между мышкой и башней в градусах
- mAngleD = mAngle / Math.PI * 180;
- //сколько градусов нехватает для полного поворота на мышь
- dAngleD = body._rotation - mAngleD;
- //без этой проверки башня будет неправильно крутиться
- //при переходе границы -180 и +180 градусов
- if (dAngleD > 180) {
- dAngleD = -360 + dAngleD;
- } else if (dAngleD < -180) {
- dAngleD = 360 + dAngleD;
- }
- //поворачиваем башню с нашей скоростью
- if(Math.abs(dAngleD) < rotToMouseSpeed) {
- body._rotation -= dAngleD;
- } else if(dAngleD > 0) {
- body._rotation -= rotToMouseSpeed;
- } else {
- body._rotation += rotToMouseSpeed;
- }
- }
- //------------------------------------------------
- var step = 2;
- var rotDirSpeed = 5;
- var rotToMouseSpeed = 7;
- onEnterFrame = function () {
- if (Key.isDown(Key.LEFT)) {
- hero._rotation -= rotDirSpeed;
- } else if (Key.isDown(Key.RIGHT)) {
- hero._rotation += rotDirSpeed;
- }
- var mDx = _xmouse - hero._x;
- var mDy = _ymouse - hero._y;
- //угол поворота между клипом hero и мышкой в градусах
- var mAngleD = Math.atan2(mDy, mDx) / Math.PI * 180;
- //угол поворота между башней и мышкой в градусах
- var dAngleD = hero._rotation + hero.body._rotation - mAngleD;
- //без этой проверки башня будет неправильно крутиться
- //при переходе границы -180 и +180 градусов
- if (dAngleD > 180) {
- dAngleD = -360 + dAngleD;
- } else if (dAngleD < -180) {
- dAngleD = 360 + dAngleD;
- }
- //поворачиваем башню с нашей скоростью
- if(Math.abs(dAngleD) < rotToMouseSpeed) {
- hero.body._rotation -= dAngleD;
- } else if(dAngleD > 0) {
- hero.body._rotation -= rotToMouseSpeed;
- } else {
- hero.body._rotation += rotToMouseSpeed;
- }
- //проверка на реализм поворота корпуса человека
- if(hero.body._rotation < -90) {
- hero.body._rotation = -90;
- } else if(hero.body._rotation > 90) {
- hero.body._rotation = 90;
- }
- var dirAngle = hero._rotation / 180 * Math.PI;
- if (Key.isDown(Key.UP)) {
- hero.foot.play();
- hero._x += step * Math.cos(dirAngle);
- hero._y += step * Math.sin(dirAngle);
- } else if (Key.isDown(Key.DOWN)) {
- hero.foot.play();
- hero._x -= step * Math.cos(dirAngle);
- hero._y -= step * Math.sin(dirAngle);
- } else {
- hero.foot.stop();
- }
- };
- onMouseDown = function () {
- hero.body.play();
- };
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- import flash.display.BitmapData;
- step = 2;
- //переводим зону проходимости в пиксельный вид
- var pathBD = new BitmapData(path._width, path._height, false, 0x000000);
- pathBD.draw(path);
- path._visible = false;
- onEnterFrame = function () {
- var dx = _xmouse - man._x;
- var dy = _ymouse - man._y;
- var angle = Math.atan2(dy, dx);
- var dist = Math.sqrt(dx * dx + dy * dy);
- if (dist > step) {
- tgtX = man._x + step * Math.cos(angle);
- tgtY = man._y + step * Math.sin(angle);
- //Если цвет пиксела черный, значит препятствие
- if (pathBD.getPixel(tgtX, tgtY) == 0) {
- var dAngle = dAngleRadian(direction, angle);
- workAngle = angle + dAngle * .8;
- var outFlag = false;
- for (var i = 0; i < 360 && !outFlag; i += 15) {
- for (var j = -1; j <= 1; j += 2) {
- var a = workAngle + radian(i) * j;
- var tempX = man._x + step * Math.cos(a);
- var tempY = man._y + step * Math.sin(a);
- if (pathBD.getPixel(tempX, tempY) != 0) {
- tgtX = tempX;
- tgtY = tempY;
- break;
- }
- }
- }
- }
- var timeDx = tgtX - man._x;
- var timeDy = tgtY - man._y;
- direction = Math.atan2(timeDy, timeDx);
- var dAngle = dAngleDegree(direction * 180 / Math.PI, man._rotation);
- man._rotation += dAngle * .2;
- man._x = tgtX;
- man._y = tgtY;
- play();
- } else {
- gotoAndStop(5);
- }
- };
- function dAngleRadian (a1, a2) {
- var da = a1 - a2;
- if (da > Math.PI) {
- da = -Math.PI * 2 + da;
- } else if (da < -Math.PI) {
- da = Math.PI * 2 + da;
- }
- return da;
- };
- function dAngleDegree(a1, a2) {
- var da = a1 - a2;
- if (da > 180) {
- da = -360 + da;
- } else if (da < -180) {
- da = 360 + da;
- }
- return da;
- };
- function degree(a) {
- return a / Math.PI * 180;
- };
- function radian(a) {
- return a / 180 * Math.PI;
- };
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- //Шаг за 1 кадр
- step = 2;
- onEnterFrame = function(){
- var dx = _root._xmouse - man._x;
- var dy = _root._ymouse - man._y;
- if (Math.abs(dx) > step) {
- var tgtX = man._x + ((dx > 0)? step : -step);
- }
- if (Math.abs(dy) > step) {
- var tgtY = man._y + ((dy > 0)? step : -step);
- }
- //Запоминаем положение
- oldX = man._x;
- oldY = man._y;
- //Смещаемся если новые координаты попадают в зону
- if (path.hitTest(man._x, tgtY, true)) {
- man._y = tgtY;
- }
- if(path.hitTest(tgtX, man._y, true)) {
- man._x = tgtX;
- }
- timeDx = man._x - oldX;
- timeDy = man._y - oldY;
- if(timeDx==0 && timeDy==0) {
- //Если не было смещения - в кадр где стоим
- man.gotoAndStop(5);
- }else {
- man.play();
- //Поворачиваемся по ходу движения
- rot = Math.atan2(timeDy, timeDx)*180/Math.PI;
- man._rotation = rot;
- }
- }
- //-----------------------------------------------------
- step = 2;
- onEnterFrame = function(){
- var dx = _xmouse - man._x;
- var dy = _ymouse - man._y;
- var angle = Math.atan2(dy, dx);
- var dist = Math.sqrt(dx*dx + dy*dy);
- if(dist > step) {
- tgtX = man._x + step * Math.cos(angle);
- tgtY = man._y + step * Math.sin(angle);
- man._rotation = angle*180/Math.PI;
- if (path.hitTest(tgtX, tgtY, true)) {
- man._x = tgtX;
- man._y = tgtY;
- man.play();
- } else {
- man.gotoAndStop(5);
- }
- }
- }
- //-----------------------------------------------------
- step = 2;
- onEnterFrame = function(){
- var dx = _xmouse - man._x;
- var dy = _ymouse - man._y;
- //Направление (угол) к цели
- var angle = Math.atan2(dy, dx);
- var dist = Math.sqrt(dx*dx + dy*dy);
- if(dist > step) {
- //пробуем пройти напролом
- tgtX = man._x + step * Math.cos(angle);
- tgtY = man._y + step * Math.sin(angle);
- if (!path.hitTest(tgtX, tgtY, true)){
- //напролом не получилось, вычисляем базовое направление
- var dAngle = dAngleRadian(direction, angle);
- workAngle = angle + dAngle*.8;
- //Шаг поворота - 10 градусов
- for(var i = 0; i < 360; i += 10) {
- for(var j = -1; j <= 1; j += 2) {
- var a = workAngle + radian(i) * j;
- var tempX = man._x + step * Math.cos(a);
- var tempY = man._y + step * Math.sin(a);
- if (path.hitTest(tempX, tempY, true)) {
- //точка выхода найдена. Запоминаем ее и прерываем цикл
- tgtX = tempX;
- tgtY = tempY;
- break;
- }
- }
- }
- }
- var timeDx = tgtX - man._x;
- var timeDy = tgtY - man._y;
- //направление движения
- direction = Math.atan2(timeDy, timeDx);
- var dAngle = dAngleDegree(direction*180/Math.PI, man._rotation);
- //поворячиваем клип к направлени движения на 5-ю часть
- man._rotation += dAngle * .2;
- man._x = tgtX;
- man._y = tgtY;
- man.play();
- } else {
- //стоим
- man.gotoAndStop(5);
- }
- }
- function dAngleRadian(a1, a2) {
- var da = a1 - a2;
- if (da > Math.PI) {
- da = -Math.PI*2 + da;
- } else if (da < -Math.PI) {
- da = Math.PI*2 + da;
- }
- return da;
- }
- function dAngleDegree(a1, a2) {
- var da = a1 - a2;
- if (da > 180) {
- da = -360 + da;
- } else if (da < -180) {
- da = 360 + da;
- }
- return da;
- }
- function degree(a) {
- return a / Math.PI * 180;
- }
- function radian(a) {
- return a / 180 * Math.PI;
- }
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- lev = 0;
- gravity = 1;//величина гравитации подбирается (визуально зависит от frameRate)
- function placeTarget() {
- lev++;
- var d = target.duplicateMovieClip("t" + lev, lev);
- d.speedY = -15 - Math.random() * 5;//начальные значения скорости
- d.speedX = Math.random() * 4;// плюс небольшой разброс
- d.rotSpeed = (Math.random() - .5) * 20;//случайный шаг для вращения
- if (Math.random() < .5) {
- d.speedX = -d.speedX;//больше разницы - отражаем бутылку по горизонтали
- }
- d.onEnterFrame = function() {
- this.speedY += gravity;
- this._y += this.speedY;
- this._x += this.speedX;
- this._rotation += this.rotSpeed;
- if (this._y > target._y) {
- this.removeMovieClip();//удаляем если улетела ниже экрана
- }
- };
- }
- count = 0;
- onEnterFrame = function () {
- if (count++ > 15) {//добавляем бутылку каждый 15-й кадр
- count = 0;
- placeTarget();
- }
- };
- //--------------------------------------------------------
- score = 0;
- all = [];//тут хранятся все летающие объекты
- lev = 0;
- gravity = 1;
- pos = 0;
- neg = 0;
- count = 0;
- crash._visible = false;
- cursor.swapDepths(12002432);//прицел выше всех бутылок
- Mouse.hide();
- function placeTarget() {
- lev++;
- var d = target.duplicateMovieClip("t" + lev, lev);
- d.speedY = -15 - Math.random() * 5;
- d.speedX = Math.random() * 4;
- d.rotSpeed = (Math.random() - .5) * 20;
- d._x = box._x + Math.random() * box._width;
- if (Math.random() < .5) {
- d.speedX = -d.speedX;
- }
- if ((Math.random() < .5 && pos < 1) || neg >= 5) {
- d.gotoAndStop(1);
- pos++;
- neg = 0;
- } else {
- d.gotoAndStop(2);
- var t = Math.random();
- if(t < .33) {
- d.obj.gotoAndStop(1);
- } else if(t < .66) {
- d.obj.gotoAndStop(2);
- } else{
- d.obj.gotoAndStop(3);
- }
- neg++;
- pos = 0;
- }
- d.onEnterFrame = function() {
- this.speedY += gravity;
- this._y += this.speedY;
- this._x += this.speedX;
- this._rotation += this.rotSpeed;
- if (this._y > box._y) {
- removeObj(this);
- this.removeMovieClip();
- }
- };
- all.push(d);
- }
- function removeObj(obj){
- var i = all.length;
- while(i--) {
- if(all[i] == obj) {
- all.splice(i, 1);
- }
- }
- }
- function placeCrash(x, y, _t) {
- lev++;
- var d = crash.duplicateMovieClip("c" + lev, lev);
- d.type = _t;
- d._x = x;
- d._y = y;
- }
- onEnterFrame = function () {
- if (count++ > 15) {
- count = 0;
- placeTarget();
- }
- cursor._x = _xmouse;
- cursor._y = _ymouse;
- };
- onMouseDown = function(){
- cursor.play();//анимация выстрела
- var i = all.length;
- while(i--) {
- var curT = all[i];
- if(curT.hitTest(_root._xmouse, _root._ymouse, true)) {
- if(curT._currentframe == 1) {
- var type = 1;
- } else{
- var type = curT.obj._currentframe + 1;
- }
- placeCrash(curT._x, curT._y, type);
- if(curT._currentframe == 2) {
- score += 20;
- if(score >= 100) {
- trace("Вы победили");
- }
- }else {
- score -= 25;
- score = (score < 0)? 0 : score;
- }
- curT.removeMovieClip();
- all.splice(i, 1);
- }
- }
- }
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- WIDTH = zone._width;
- HEIGHT = zone._height;
- LEFT = zone._x;
- TOP = zone._y;
- RIGHT = LEFT + WIDTH;
- BOTTOM = TOP + HEIGHT;
- speed = 0;
- speedLimit = 8;
- speedStep = .5;
- rotLimit = 35;
- rotStep = 3;
- trailerRotLimit = 55 / 180 * Math.PI;
- processKey = function () {
- if (Key.isDown(Key.CONTROL) || Key.isDown(Key.SPACE)) {
- car.kovsh.play();
- }
- if (Key.isDown(Key.LEFT)) {
- if (car.left._rotation > -rotLimit) {
- car.left._rotation = car.right._rotation -= rotStep;
- }
- } else if (Key.isDown(Key.RIGHT)) {
- if (car.left._rotation < rotLimit) {
- car.left._rotation = car.right._rotation += rotStep;
- }
- }
- if (Key.isDown(Key.UP)) {
- speed += (speed < speedLimit)? speedStep : 0;
- } else if (Key.isDown(Key.DOWN)) {
- speed += (speed > -speedLimit)? -speedStep : 0;
- } else {
- speed += (speed < 0)? speedStep : (speed > 0)? -speedStep : 0;
- }
- };
- checkCycle = function () {
- bounds = car.getBounds(this);
- boundWidth = bounds.xMax - bounds.xMin;
- boundHeight = bounds.yMax - bounds.yMin
- if(bounds.xMax < LEFT) {
- car._x = RIGHT + car._x - bounds.xMin;
- } else if(bounds.xMin > RIGHT) {
- car._x = LEFT - (bounds.xMax - car._x);
- }
- if(bounds.yMax < TOP) {
- car._y = BOTTOM + (car._y - bounds.yMin);
- } else if(bounds.yMin > BOTTOM) {
- car._y = TOP - (bounds.yMax - car._y);
- }
- };
- function move(){
- if(Math.abs(speed) > 0) {
- car._rotation += car.left._rotation * speed / car.left._x;
- }
- angle = car._rotation * Math.PI / 180;
- speedX = speed * Math.cos(angle);
- speedY = speed * Math.sin(angle);
- car._x += speedX;
- car._y += speedY;
- }
- function correctTrailer(slave, master){
- if(speed){
- //Пересчитываем точку в родительскую систему координат
- var masterDot = {x:master.dotOut._x, y:master.dotOut._y};
- master.localToGlobal(masterDot);
- globalToLocal(masterDot);
- var dx = masterDot.x - slave._x;
- var dy = masterDot.y - slave._y;
- //Угол между прицепом и машиной
- var aRad = Math.atan2(dy, dx);
- //Угол поворота самой машины
- var masterRotRad = master._rotation / 180 * Math.PI;
- //Разница между ними
- var dAngle = masterRotRad - aRad;
- //Коррекция перехода 180/-180 градусов
- if (dAngle > Math.PI) {
- dAngle = -Math.PI*2 + dAngle;
- } else if (dAngle < -Math.PI) {
- dAngle = Math.PI*2 + dAngle;
- }
- if(speed < 0) {
- //Выполняется только при движении назад
- //Ограничение на поворот и торможение из-за прицепа
- if(dAngle >= trailerRotLimit) {
- aRad = masterRotRad - trailerRotLimit;
- speed *= .8;
- } else if(dAngle <= -trailerRotLimit) {
- aRad = masterRotRad + trailerRotLimit;
- speed *= .8;
- }
- //Обратная связь на машину в результате торможения
- //Коэффициенты .5 и 3 подбираются вручную
- if(dAngle >= trailerRotLimit * .5) {
- master._rotation += speed / speedLimit * 3;
- } else if(dAngle <= -trailerRotLimit * .5) {
- master._rotation -= speed / speedLimit * 3;
- }
- }
- //Убираем паразитную скорость (погрешность округления чисел)
- if(Math.abs(speed) < speedStep && !Key.isDown(Key.DOWN)) {
- speed = 0;
- }
- //Поворачиваем прицеп к машине
- var a = aRad / Math.PI * 180;
- slave._rotation = a;
- //Пододвигаем прицеп чтобы была стыковка
- slave._x = masterDot.x - Math.cos(aRad) * slave.dotIn._x;
- slave._y = masterDot.y - Math.sin(aRad) * slave.dotIn._x;
- }
- }
- onEnterFrame = function() {
- processKey();
- move();
- checkCycle();
- correctTrailer(trailer, car);
- }
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- -------------------------------------------------------
- lev = 0;
- speedY = 5;
- dot._visible = false;//скрываем оригинал
- placeDot = function() {
- lev++;
- d = dot.duplicateMovieClip("d" + lev, lev);
- d._x = Math.random()* 40 - 20;//случайное положение - разброс
- d._y = Math.random()* 16 - 8;
- d._xscale = d._yscale = 50 + Math.random() * 50;
- d.onEnterFrame = function() {
- this._y -= speedY;
- this._xscale = this._yscale *= .96;
- if(this._xscale < 2) {
- this.removeMovieClip();
- }
- }
- }
- onEnterFrame = placeDot;
- //-----------------------------------------------
- dot._visible = false;
- lev = 0;
- placeDot = function() {
- lev++;
- var d = dot.duplicateMovieClip("b" + lev, lev);
- d.speed = 1 + Math.random() * .5;//скорость
- d.a = 1 + Math.random() * 1;//амплитуда качания по _x
- d.s = .001 + Math.random() * .08;//скорость качания
- d.t = Math.random() * 10;//случайное начальное положение для синуса
- d.y0 = d._y += Math.random() * 2 - 1;//разброс по _y
- d.x0 = d._x += Math.random() * 2 - 1;//разброс по _x
- d._xscale = d._yscale = 50 + Math.random() * 50;//случайный размер
- d.onEnterFrame = function() {
- this._y -= this.speed;
- this.a += this.s;//амплитуда немного увеличивается со временем
- this._x = this.x0 + this.a * Math.sin(this.t += this.s);
- this._xscale = this._yscale *= .99;//а размер немного уменьшается (хуже видно)
- if(this._xscale < 2) {
- this.removeMovieClip();
- }
- }
- }
- onEnterFrame = placeDot;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement