![]() |
|
||||||||||
|
|||||
|
Регистрация: Feb 2009
Сообщений: 34
|
Делаю игру, в игре несколько уровней, в них одинаковая механика. Расскажите пожалуйста, как правильно организовать код и где его разместить? Проблема в том, что вроде как функции можно определять только в кадрах. Соответственно, если я перейду на другой кадр, где находится графика для следующего уровня, флеш не увидит моих функций. Не копировать же их для каждого кадра? Спасибо.
|
|
|||||
|
Banned
[+5 15.02.09]
[++5 15.02.09] Регистрация: Mar 2008
Адрес: Krasnoyarsk
Сообщений: 587
|
Не рисовать графику в кадрах, и не писать код в кадрах.
|
|
|||||
|
Vogd, изучите работу с Классами, и генерацию уровней посредствам кода...
|
|
|||||
|
Цитата:
Добавьте графику в библиотеку в виде мувиклипов, а затем просто напишите функцию, которая бы собирала уровень из имеемых кусочков
__________________
...вселенская грусть |
|
|||||
|
Регистрация: Feb 2009
Сообщений: 34
|
Классы поизучаю, спасибо.
Не понимаю - создавать уровни в кадрах это плохо? Как тогда делать уровни в играх типа этой: http://armorgames.com/play/3194/roly-poly-cannon ? |
|
|||||
|
каждый последующий уровень собираешь на месте прпедыдущего (элементы старого удалил, новый собрал), для сборки можно использовать массив типа : элемент, его координаты и свойства.
|
|
|||||
|
Регистрация: Feb 2009
Сообщений: 7
|
Здравствуйте . Покажите пример как сделать переход во второй уровень чтоб не осталось объектов из первого . В зтом движке.
startGame(); stop(); function startGame() { // establish constants floor = 350; foxSpeed = 10; bunnySpeed = 2; jumpPower = 60; // initialize fox foxPos = {x:0,y:0}; fallSpeed = 0; falling = false; fox.swapDepths(999); // moveFox should be called every frame _root.onEnterFrame = moveFox; // create the objects in the world createWorld(); createObjects(); } function createWorld() { objects = new Array(); objects.push({type:"box", x:250, y:0}); objects.push({type:"box", x:300, y:0}); objects.push({type:"bunny", x:400, y:0}); objects.push({type:"bunny", x:1200, y:0}); worldEnd = 1400; } function createObjects() { for(var i=0;i<objects.length;i++) { _root.attachMovie(objects[i].type,"object "+i,i); } } function moveFox() { // get movement bounds for fox foxBounds = determineBounds(foxPos); // if no ground under fox, then start falling if ((foxBounds.bottom > 0) and (!falling)) falling = true; // fall if (falling) checkFall(); // left arrow, move left if no boundary hit if (Key.isDown(Key.LEFT)) { if (foxSpeed < foxBounds.left) { foxPos.x -= foxSpeed; } if (foxPos.x < 0) foxPos.x = 0; fox._xscale = 25; moving = true; // right arrow, move right if no boundary hit } else if (Key.isDown(Key.RIGHT)) { if (foxSpeed < foxBounds.right) { foxPos.x += foxSpeed; } if (foxPos.x > worldEnd) foxPos.x = worldEnd; fox._xscale = -25; moving = true; // must not be moving } else { moving = false; } // if on the ground and spacebar hit, then jump if (Key.isDown(Key.SPACE) and (!falling)) { fallSpeed = jumpPower; // jump = fall up falling = true; if (!moving) { // use jump animation only if not moving fox.gotoAndPlay("jump"); } } // if moving and not falling, animate if (moving and !falling) { fox.nextFrame(); // if not moving or falling, then show stand frame } else if (!moving and !falling) { fox.gotoAndStop(1); } // position fox movie clip vertically fox._y = floor - foxPos.y; // bunnies get their turn to move moveBunnies(); // draw all objects according to new positions drawObjects(); // see whether any acorns are hit getAcorns(); } function determineBounds(pos) { // assume distance bounds, ground is bottom var bounds = {left:1000,right:1000,top:1000,bottom:pos.y}; // loop through all objects for(var i=0;i<objects.length;i++) { // only look at boxes if (objects[i].type == "box") { var dx = objects[i].x - pos.x; var dy = objects[i].y - pos.y; // if box is in same vertical space if ((dy >= 0) and (dy <= 50)) { // if box to the to left, see whether it is closest so far if ((dx+50 <= 0) and (Math.abs(dx+50) < bounds.left)) { bounds.left = Math.abs(dx+50); // if box is to the right, see whether it is closest so far } else if ((dx >= 0) and (dx < bounds.right)) { bounds.right = dx-50; } } // box is in same horizontal space if ((dx >= -50) and (dx <= 50)) { // if box is below, see whether it is closest so far if ((dy+50 <= 0) and (Math.abs(dy+50) <= bounds.bottom)) { bounds.bottom = Math.abs(dy+50); // if box is above, see whether it is closest so far } else if ((dy-50 >= 0) and (dy-50 < bounds.top)) { bounds.top = dy-50; } } } } return(bounds); } function checkFall() { // accelerate due to gravity fallSpeed -= 10; // room to fall at full speed if (fallSpeed > -foxBounds.bottom) { foxPos.y += fallSpeed; // complete distance to ground and stop falling } else { foxPos.y -= foxBounds.bottom; fallSpeed = 0; falling = false; fox.gotoAndStop(1); // stand } // see whether fox hits head on box above if (foxPos.y > foxBounds.top) { foxPos.y = foxBounds.top; fallSpeed = 0; } } function drawObjects() { // loop through all objects for(var i=0;i<objects.length;i++) { // set horizontal position according to where fox is _root["object "+i]._x = x = 275 + objects[i].x - foxPos.x; // set vertical position according to floor _root["object "+i]._y = floor - objects[i].y; } } function getAcorns() { // loop through all objects looking for points for(var i=objects.length-1;i>=0;i--) { if (objects[i].type == "acorn") { // if within 30 pixels, player got it if (distance(_root["object "+i],fox) < 30) { _root["object "+i].play(); objects[i].type = "used"; score += 100; } } } } // utility function to determine actual distance between movie clips function distance(mc1,mc2) { d = Math.sqrt(Math.pow(mc1._x-mc2._x,2)+Math.pow(mc1._y-mc2._y,2)); return d; } function moveBunnies() { // loop through all objects looking for bunnies for(var i=objects.length-1;i>=0;i--) { if (objects[i].type == "bunny") { // move only bunnies on screen if (Math.abs(objects[i].x-foxPos.x) < 275) { // move toward fox if (foxPos.x < objects[i].x) { var dx = -bunnySpeed; } else if (foxPos.x > objects[i].x) { var dx = bunnySpeed; } // determine bounds for this bunny bunnyBounds = determineBounds(objects[i]); // move only as far as bounds if ((dx < 0) and (bunnyBounds.left > Math.abs(dx))) { objects[i].x += dx; } else if ((dx > 0) and (bunnyBounds.right > Math.abs(dx))) { objects[i].x += dx; } // see whether bunny is close enough to fox if (distance(_root["object "+i],fox) < 30) { _root.onEnterFrame = undefined; gotoAndPlay(10); } } } } } Здесь в конце кода я хочу чтоб появлялся кран "game over" который находится на 10 кадре .Он появляется ,но все объекты из этапа остаются видимыми. Я могу убрать только Фокс а как написать ремув для остальных объектов которые на сцену устанавливает код ? |
|
|||||
|
Нуб нубам
модератор форума
Регистрация: Jan 2006
Адрес: Бердск, НСО
Сообщений: 6,445
|
__________________
Reality.getBounds(this); |
|
|||||
|
Регистрация: Feb 2009
Сообщений: 7
|
Wolsh , что то не получается. Посмотри пожалуйста исходник.
|
|
|||||
|
Нуб нубам
модератор форума
Регистрация: Jan 2006
Адрес: Бердск, НСО
Сообщений: 6,445
|
Описать функцию мало - ее еще надо вызвать))) Прямо перед gotoAndPlay(10).
И да, если у Вас АС1 - уберите тип данных из определения переменной dead (:MovieClip), иначе работать не будет. И - "О, боже!" - ПРОБЕЛ в имени клипа???? Как я сразу не углядел, копируя))) Немедленно уберите все пробелы из _root["object "+i];
__________________
Reality.getBounds(this); |
![]() |
![]() |
Часовой пояс GMT +4, время: 17:20. |
|
|
« Предыдущая тема | Следующая тема » |
| Опции темы | |
| Опции просмотра | |
|
|