![]() |
Плавное перемещение объекта
Есть объект с координатами х=283 у=270. Надо его по нажатию кнопки плавно переместить в х=96 у=334
Как посредством actionscript это сотворить? Книжку по флэшу отдала а мозгов видимо не хватает. :confused: |
onClipEvent(load){
angle_rad=Math.atan2((y1-y2), (x1-x2)); dy=Math.sin(angle_rad); dx=Math.cos(angle_rad);} onClipEvent(enterFrame){ if(кнoпканажата){ if(_x<x1&&_y<y1){ _x+=dx; _y+=dy; } } } Вот так приблизительно. |
огромное спасибо, но вот вопрос.
а "оно" его будет перемещать по прямой или по дуге? мне надо по прямой... |
У меня похожий вопрос есть...
Мне нужно приблизительно тоже самое, но только чтобы оьект колебался возле нового центра.
Например вот такая задача. Где то помещается клип. Для негно задется скорость, и координата назначения. Он к ней стремится и поколебавшись около нее останавливается. Что-то не могу вспомнить как это посчиать. Давно школу закончил :) |
2 комарик а откуда там дуге взятся
2 bolt начальную :) |
Именно начальную...
Я проработав 10 лет в области компьютерной графики и думать не мог, что когда-нибудь мне понадобиться вспоминать тригонометрию. Но вот погрузился во флеш и понял, что ошибался.
Чем огрызаться лучше бы помог. У меня справочников под рукой нету, а товарищи по работе все сплошные менеджеры да художники (как и я). Хоть одного бы программиста - они с математикой дружны, обычно. |
это не тригонометрия, а аналитическая геометрия на плоскости, или линейная алгебра
МГУЛ - ПМ - РУЛЕЗ!!! :D |
2Carzy Blot
движение до заданной точки можно сделать как написал шаман: считаем угол наклона траектории через арктангенс (отношение разностей соответствующих координат), и по найденному углу через синус и косинус вычисляем каждую следующую точку с заданным шагом. теперь затухание. теория. общая формула колебательного процесса (начальный сдвиг фазы выбросили): x = centerpoint.x + A*cos(wt); y = centerpoint.y + A*sin(wt); ...то есть 't' - параметр, постоянно растет, а 'w' - циклическая частота (количество периодов за единицу времени) чтобы гармонические колебания затухали, нужно уменьшать амплитуду 'A'... можно сделать экспоненциальное затухание (вроде A = C*exp(-t/T); где t - это тот же параметр, C - начальное значение амплитуды, а 'T' - начальное значение параметра 't') а можно и просто линейное. можно, к примеру, сделать A *= 0.9; тогда каждое следующее значение амплитуды будет на одну десятую меньше предыдущего, что естесственно приведет к затуханию... 1:11 по мск времени :) примерчик делать влом :) если нужно, то завтра... или может шаман или лизергиль разродится :) |
Вот скрипт
/*Этот скрипт - к любому мувику.
Хрестоматийный пример bounce . Только ещё как Bonus - можно делать драг мышью*/ onClipEvent (mouseDown) { // drag the object if the cursor is over it and mouse is clicked if (hitTest(_root._xmouse, _root._ymouse, true)) { startDrag (""); set ("_parent.press" add this._name, true); // get the location of this object when picked up xLoc = this._x; yLoc = this._y; // get the time timePressed = getTimer(); } } onClipEvent (mouseUp) { stopDrag (); set ("_parent.press" add this._name, false); // checking the timer, we can find out: // did the user throw the object, or just pick it up and carry it? if (getTimer()<timePressed+300) { // they definitely threw the object. // what is the new location of this object? xNewLoc = this._x; yNewLoc = this._y; // how hard did they throw it? xTravel = xNewLoc-xLoc; yTravel = yNewLoc-yLoc; // setting the speed of the object depending on how far they travelled with it xInc = xTravel/2; yInc = yTravel/2; timePressed = 0; } else if (getTimer()>timePressed+300) { // they did not throw the object, just carried it, so don't move it xInc = 0; yInc = 0; } } onClipEvent (enterFrame) { hit = false; for (objects in _parent) { // check out all of the other objects, are they touching this one? if (hitTest(eval("_root." add objects add "._x"), eval("_root." add objects add "._y"), true) && objects != this._name) { hit = true; } if (hit == true && objects != this._name) { // an object is touching this one, but where is it? if (eval("_root." add objects add "._y")<this._y) { // if the colliding object is above this one, // we have to allow it to bounce to the left or right if necessary offset = (this._x-eval("_root." add objects add "._x")); set ("_root." add objects add ".xInc", eval("_root." add objects add ".xInc")+offset); xInc = xInc+offset; } // we find out how hard the other object hit this one // the impact of that object affects the speed of this object xIncHit = eval("_root." add objects add ".xInc"); yIncHit = eval("_root." add objects add ".yInc"); yInc = yInc+yIncHit; xInc = xInc+xIncHit; this._x = this._x+xIncHit; this._y = this._y+yIncHit; // when an object hits another, its speed is reversed. here, we just send the object // in the other direction, at the same speed it was travelling when it hit this one // // we don't know which object hit us, so we just find out the name of the last thing // that hit us, and set its movement values to the opposite of what it was before set ("_root." add objects add ".xInc", eval("_root." add objects add ".xInc")*(-1)); set ("_root." add objects add ".yInc", eval("_root." add objects add ".yInc")*(-1)); hit = false; } } // time to make the object move if (eval("_parent.press" add this._name) != true) { // the speed increment becomes 94% of itself in each iteration. this is our "friction". // it may or may not be scientific, but it looks realistic xInc = xInc*.94; yInc = yInc*.94; // ditto for gravity. we need something to make the object(s) drop towards the bottom gravity = 3; yInc = yInc+gravity; // these next two lines are actually the core movement of this object this._y = this._y+yInc; this._x = this._x+xInc; // set up the bounds for bouncing objects leftBound = 0; rightBound = 550; topBound = 0; bottomBound = 400; // if the object goes off bounds, send it back and reverse its travel speed if (this._x>rightBound) { this._x = rightBound; xInc = -xInc; } else if (this._x<leftBound) { this._x = leftBound; xInc = -xInc; } else if (this._y>bottomBound) { this._y = bottomBound; yInc = -yInc; } else if (this._y<topBound) { this._y = topBound; yInc = -yInc; } } } |
Спасибо буду разбираться...
Справочник нарыл заодно. Что-то начало смутно вспылвать из пучин забвения.
|
| Часовой пояс GMT +4, время: 07:53. |
Copyright © 1999-2008 Flasher.ru. All rights reserved.
Работает на vBulletin®. Copyright ©2000 - 2026, Jelsoft Enterprises Ltd. Перевод: zCarot
Администрация сайта не несёт ответственности за любую предоставленную посетителями информацию. Подробнее см. Правила.