Tracking Forums, Newsgroups, Maling Lists
Home Scripts Tutorials Tracker Forums
  Advanced Search
  HOME    TRACKER    Flash




Mouse Velocity



Is there a way I could get the velocity of the mouse movement?



FlashKit > Flash Help > Flash ActionScript
Posted on: 06-02-2003, 10:34 PM


View Complete Forum Thread with Replies

See Related Forum Messages: Follow the Links Below to View Complete Thread

Q: Velocity Of Mouse
Hi
I'm trying to create a process clip that captures the absolute velocity (taking into account both x and y directions) of the mouse.
Can anyone help me out here?

Mouse Velocity Calculation?
Hi,

Just as an experiment I want to calculate the speed that the pointer is moving at. Now I remebered from my physics GCSE days -

velocity = distance/time;

So I was thinking along the lines of:

on a mouse move event
store the mouse x and y positions
start a timer

when the mouse comes to rest (hmm how do I tell this? I need tot hink about that)
stop the timer
store the new mouse x and y positions

then do the calc.


It works in theory - Would it work in practice???

I'm going to go experiment with that, anyone else got any ideas on how do this??

Cheers people,

Stu

Calculating Mouse Velocity
Hi-

I want to calculate the mouse velocity, any ideas how I could do this?

i've searched and searched this forum..

i'm assuming I could call the mouse position and a few miliseconds later i could call it again calculate the difference between the two and then divide it by the time difference?

is that right?

I have no idea how i would do that though.

thanks in advance,

dom

Track Mouse Velocity
Is there a better way to do this?


ActionScript Code:
var mDown:Boolean = false;
 
checkX = function (dx, oldVal, newVal) {
    var v:Number = Math.abs(oldVal-newVal);
    if (v>10) {
        if (oldVal<newVal) {
            //trace("moving right");
        } else if (oldVal>newVal) {
            //trace("moving left");
        }
    }
    return newVal;
};
this.watch("xdir",checkX);
this.onMouseMove = function() {
    if(mDown){
        xdir = _xmouse;
    }
};
 
this.onMouseDown = function(){
    mDown = true;
}
 
this.onMouseUp = function(){
    mDown = false;
}

How To Calculate Mouse Velocity?
After watching Lee's tutorial on the on creating sound based on mouse position I was interested in using the velocity of the mouse to control the sound. Here's my thoughts on how I would attempt to calculate the velocity but I figured there had to be an easier way.

So in physics velocity is change in distance / change in time. We also know change in distance can be computed from the distance formula [ (y2-y1)^2 + (x2-x1)^2 ]^(1/2) and the change in time would be given in the program to take data on a certain interval perhaps 0.1 seconds.

In flash I would have four variables (x1, y1, interval, vel for old mouseX , old mouseY, interval, and velocity) and store the initial mouse position in them. Then a timer would start and grab mouseX and mouseY (the current live position) and store them after 0.1 seconds or whatever you set, then it would compute the velocity, and finally save the used mouseX and mouseY back to the x1 and y1 varibles to be used in the upcoming calculation at 0.2 seconds. Theres some crude pseudocode below just incase that helps anyone see what i'm trying to do but I still don't know how to get the timer to function as I need it.
Code:

var x1:Number;
var y1:Number;
var interval:Number;
var vel:Number;

x1 = mouseX;
y1 = mouseY;

// use timer code i'm not exactly sure how to code yet
// but basically every 0.1 seconds it would call the calculateVelocity function.

// the following is probably completely wrong so if it's confusing you i'm sorry
// I just want to get the idea across

var timer:Timer = new Timer( interval );
timer.addEventListener(Event.COMPLETE, calculateVelocity);

// end of my lame attempt at coding a timer


function calculateVelocity():void
{
   // calculate velocity
   vel = Math.sqrt(  Math.pow( (mouseY - y1), 2 ) + Math.pow( ( mouseX - x1 ), 2 )  );

   // overwrite old positions with the current positions for next calculation
   x1 = mouseX;
   y1 = mouseY;

  // pretty sure this next line is invalid but you get the idea.
  sound.channel.transform.volume = vel;
}

// you would also have all the rest of the junk to deal with the sound but I'm just wondering if it's feasible to calculate velocity.



two things I was worried about is if something happens to the users computer and the calculation for veloctity isn't computed in 0.1 seconds then it would throw things off. also will the mouseX and mouseY properties be changing throughout the calculations so that the ones used to calculate velocity won't necessarily be the ones reassigned to the x1 and y1 variables. I thought about storing the values locally in the timer function but i didn't know if that would help.

Anyways if your eyes found their way to the bottom without reading the rest of the ramble I just want to know how to calculate velocity of the mosue and use it to control sound. I'm thinking of having an engine or "woosh" sound which is constantly looping but the volume is linked to the mouse velocity so as you move the mouse faster your engine seems to rev up or maybe the woosh sound gets louder like when you swing a stick really fast through the air.

Mouse Follow Thingy And Max Velocity.
I am new to flash and actionscript, ive been playing and trying to make a ball follow my mouse.

I butchered someone elses actionscript that made a ball leave a trail and fly in a circle, and i got it to follow my mouse around.

But now i want to follow my mouse but with a max speed so that it doesnt get choppy if i move my mouse to fast, and it will look smoother.
How do i do this?

I thought about putting a delay on the follow but if i did that it will just be slow when the mouse is slow, and fast when the mouse is fast but a few seconds behind, right?


This is the code i have

//follows the mouse when moved

stage.addEventListener(MouseEvent.MOUSE_MOVE, mouseMove);
function mouseMove(event:MouseEvent) {
myBall.x = myBall.parent.mouseX
myBall.y = myBall.parent.mouseY
}
//Add ENTER_FRAME to the ball, so we can animate it in each frame
myBall.addEventListener (Event.ENTER_FRAME, moveBall);

//We use this timer to create a trail ball

var timer:Timer = new Timer(30,400000);
timer.addEventListener (TimerEvent.TIMER, createTrailBall);
timer.start ();

//This function is responsible for moving the ball
function moveBall (e:Event):void {
}

function createTrailBall (e:Event):void {

//Create a new ball instance
var trailBall:Ball=new Ball();

//Position the trail ball in the same position where the original ball is located
trailBall.x = myBall.x;
trailBall.y = myBall.y;

//Add ENTER_FRAME to animate the trail ball
trailBall.addEventListener (Event.ENTER_FRAME,animateTrailBall);

/*
Add the trail ball on to the stage.
We don't want to position the trail ball on top of the original ball.
We use the addChildAt method to set the index to 0.
*/
addChildAt (trailBall,0);
}

function animateTrailBall (e:Event):void {
//In each frame, reduce the alpha and the scale of the trail ball.
e.target.alpha -= 0.04;
e.target.scaleY -= 0.04;
e.target.scaleX -= 0.04;

/*
If the alpha is less than 0, we remove the trail ball from the
stage.
*/
if (e.target.alpha < 0) {
e.target.removeEventListener (Event.ENTER_FRAME,animateTrailBall);
removeChild ((MovieClip)(e.target));
}
}

Angular Velocity To Linear Velocity
Hey guys,

I've been searching the 'nets for a few days now and have been unable to come up with anything that helps.

The problem is this:

Imagine you have a small ball attached to a string. You start swinging this ball in a circular motion (such as in a centripetal force test with a bucket full of water ). As the ball rotates, it is gathering angular speed around a central point. Now let's say you let go of the string. What would the resulting initial linear velocity (x and y components) be of the ball?

I've been trying all sorts of equations and uses of sin and cosine, but to no avail.

Any ideas?

Velocity Please
I went through the tutorial section and came across one showing how to make a ball that can be "thrown" with the mouse and it bounces off the walls and there's gravity pulling it down and such. I DLed it and I believe I understand most of the code but I have a couple questions which I suspect are related to one another:

1) What on earth is that t variable doing. It looks to me like nothing.

2) How does the program distinguish between me just dragging the ball a distance and my dragging the ball QUICKLY over a distance. According to my flawed understanding of the code, I would think I could simply drag the ball a distance as slowly as I liked and it would set the velocity according the the start and end points.

To save you the trouble of going to the tutorial I will attach the file for reference.

Velocity...?
I'm not sure if this is going to be an action script or else. I am trying to have an animation that moves the slows and stops in a smooth manner. I'm sure I can use multiple motion tweens to create this effect. However, is there another way such as usin an action script that I can apply to several instances/symbols? I've seen some very smoothe yet simple animations doe. It seems to me that it doesn't have to be very complex to look good. Just looking for more information. Apreciate any help ...

Thanks
Mike

Velocity
Hello all,

I am currently developing a soccer game and am experiencing difficulty with programming the balls movement. Can anyone offer assistance with velocity and direction of the ball when it is hit by a player (movie clip). If anyone knows of any links to tutorials on this subject please send them my way!

Thanks,
Jon

Velocity And Acceleration...
Does anyone know where i can find good tutorials or open source for acceleration and velocity?i checked flashkit for them and couldn't find any.

.:: Velocity-problems ::.
hey,

I've made a flash-website on a pretty advanced computer (Pentium 4; 2,4 Ghz; HD:15000rpm)
I must admit that in any transition-animation I've made,
I changed my alpha values off the bitmaps.
Some technical specification:
size=313kb
fps=60
the animation for each topic = 30f so 0,5s
When I looked at the animation on that computer, no problems did emerge, but
when I looked at the animation on a Pentium 3; 1,0Ghz(which isn't an old computer)
the animation played almost four times longer as defined


Does anyone has an idea how I can dessolve this problem?

Velocity And Rotation
Hello,

I'm new to animation, and am starting to understand how to bounce objects, throw them, and do all sorts of fun stuff. As mentioned in my previous post, I am designing a deck of cards. I would like to be able to throw each card in a way that they will rotate when thrown. The rotation speed and direction (clockwise or counterclockwise) will depend on where the user picks up the card in relation to its center point. My theory is that I need to calculate the distance between the center of the card and the mouse pointer, and multiply that distance by a defined rotation speed. Depending on how hard the user throws the card (velocity?), the card will spin faster or slower in relation to where it was grabbed.

.... okay, I hope this makes sense.... So, what I'm actually looking for is a sample of something like this - if there is one. I think I would need to dissect an example to start to understand the physics behind something like this.

Any suggestions or comments welcome.

My throwing code is as follows (my ball mc is actually a card, so you can see the rotation):









Attach Code

init();
function init()
{
dragging = false;
friction = .01;
bounce = -0.7;
gravity = 0.5;
top = 0;
left = 0;
bottom = Stage.height;
right = Stage.width;
ball = attachMovie("ball", "ball", 0);
ball._x = Stage.width / 2;
ball._y = Stage.height / 2;
vx = Math.random() * 10 - 5;
vy = Math.random() * 10 - 5;
}
ball.onPress = function()
{
oldX = ball._x;
oldY = ball._y;
dragging = true;
ball.startDrag();
};
ball.onRelease = function()
{
dragging = false;
ball.stopDrag();
};
ball.onReleaseOutside = function()
{
dragging = false;
ball.stopDrag();
};

function onEnterFrame(Void):Void
{
if (!dragging)
{
//this section controls gravity
//vy += gravity;
//vx *= friction;
//vy *= friction;

ball._x += vx;
ball._y += vy;
if (ball._x + ball._width / 2 > right)
{
ball._x = right - ball._width / 2;
vx *= bounce;
}
else if (ball._x - ball._width / 2 < left)
{
ball._x = left + ball._width / 2;
vx *= bounce;
}
if (ball._y + ball._height / 2 > bottom)
{
ball._y = bottom - ball._height / 2;
vy *= bounce;
}
else if (ball._y - ball._height / 2 < top)
{
ball._y = top + ball._height / 2;
vy *= bounce;
}
}
else
{
vx = ball._x - oldX;
vy = ball._y - oldY;
oldX = ball._x;
oldY = ball._y;
}
}

Velocity And Angles
Hi atm I'm writing the code for a game. I can sorted Vertical and Horizontal collision. But I'm having trouble with collisions at an angle, e.g. a 45 degree ramp. My cousin says I have to work out the trajectory angle from the Xv and Yv but the closest I can get is:



PHP Code:



    playerRadins = Math.atan2 (speed_y, speed_x);    playerAng = Math.round(playerRadins * 180 / Math.PI); 




This gives me something along the lines of this.

And I'm looking for this:


Please help also if there is another way to do this just with velocity vectors please tell me how to do that instead. I think this can did it that way:

http://www.tonypa.pri.ee/vectors/tut06.html

but I can't make head nor tail of it

Heres what I have so far:
http://img99.imageshack.us/img99/959...2scrolliz7.swf

Cursor Velocity
Hi there,
does anyone would know how to calculate the velocity of speed in a animation and espetially how to make it in flash. I know the function but I can't figure how to make "detection" with clip events

thanks
Yannick

About The Velocity Of A Movie Through The Web
hi guys ... well, i have a movie in flash 7 ... and when i see it through the web the movie is too much more slow than the movie exported in the local station ... its velocity is really slow ... but seeing it locally is correct ....
maybe i could think is some problem related to the parameters inside the code of the flash object into the html ? or am i wrong ?
maybe it could be some kind of 'bug' of flash 8 or flash player 8 ? (i've got flash 8 installed ..instead i exported the movie in flash player 7 ..) or usually this happens commonly .. ?
any help will be very apreciated ..

all my gratitude ... if someone can help ... and if i didnt wrote good .. i could explain it better after ..

thanks .

Text Scroller With Velocity
sup fools!
I was surfing this funny hotpockets site and found this cool flash textbox that has velocity in the scroller. How'd they do this!? We should try and recreate it sos we'll always have it here and people can grab it. I'll start trying and posting fla's of what I got. Feel free to join in and work with me on this.

To see it in action click here:

http://www.hotpocketsdojo.com/

and goto the baby picture resting on the rock. here's a screengrab of the textbox with velocity scrolling that I wanna recreate:



ready... break!

Reversing Velocity Code
Last week I asked about adding velocity to an image that is scripted to animate and fade in from the left. This code from teh community was very helpful. Since then I have been trying to figure out a way to also make the current image animate out to the right and fade down - kinda the exact opposite so one fades in as it moves, the other leaves.

Not getting very far. Was hoping for some hints. It's seems a lot harder to think in reverse coding



Code:

/////////////////////////////////////////////////////////////////////////////////////////
// Marquee display...
/////////////////////////////////////////////////////////////////////////////////////////
var startingX:Number = 450;
var targetX:Number = 550;
var velocity:Number = 8;
var distanceX:Number;
var movementX:Number;

for (var i = 1; i <= 6; i++) {
var mc = _root["mrq_chan0" + i];
mc._alpha = 0;
}
//////////////////////////////////////////////////////////
function showMarquee(channelIn, channelOut) {
//reset position back to starting point
channelIn._x = startingX;

// Set alpha to zero for all channels...
for (var i = 1; i <= 6; i++) {
var mc = _root["mrq_chan0" + i];
delete mc.onEnterFrame;
mc._alpha = 0;
}

// Assign action to perform on every frame of MovieClip
channelIn.onEnterFrame = function():Void {
// Fade up...
channelIn._alpha += 4;

// distance to target is the target's X minus the MovieClip's current X position
distanceX = targetX - channelIn._x;
movementX = distanceX / velocity;
channelIn._x += movementX;

// if mc has reached destination, remove action
if (Math.abs(channelIn._x - targetX) < 1) {
delete channelIn.onEnterFrame;
}
};
}

Velocity Not Calculating Correctly
ok so I have the following code, assume that onLoad dx = 0 and moving = false

for some reason when I go right, it goes twice the speed(visibly) but traces 5. and when the !moving kicks in it slows down at twice the rate, and left works fine, unless it slows down at half the rate and the Key.RIGHT is correct on its deaccel and just looks wrong becuase of its initial speed.

is there something in my numbers that is off?


oh..I forgot part of the code...here's the right code....

Code:
if(Key.isDown(Key.RIGHT)){
dx = 5;
_x += dx;
moving = true;
}
else{
moving = false;
}
if(Key.isDown(Key.LEFT)){
dx = -5;
_x += dx;
moving = true;
}
else{
moving = false;
}
if(!moving){
if(dx < 0){
dx += .1;
_x += dx;
}
else if(dx > 0){
dx -= .1;
_x += dx;
}
else{
dx = 0;
}
}
}

Sync Sound With Mc Velocity?
I'm working on a project that incorporates an mc that looks like a big "Wheel of Fortune" prize wheel. You can click/drag to rotate the wheel. My goal is to hook this rotation up to a sound file (single click sound) that syncs/corresponds to the speed of rotation, so that when you grab and move it quickly, the clicks repeat at a fast rate, and as it slows down, the clicks slow with the wheel speed until eventually they stop when the wheel stops.

Any ideas on how to execute greatly appreciated!

Projection Of Velocity + Gravity
I am making a game similar to worms, and i was wondering if there is a way to calculate a curved line from the velocity, gravity, wind etc.

This way i can check where it is going to land.

The only way i can think of is a while loop and updating the calculated position, and making a curved line from lots of smaller straight lines.

Is it possible to do this without the loop? and have a "pure" curved line.

Velocity/collision Detection?
hey guys...been struggling with this for weeks now...finally give up...please help....

I have MCS moving on stage with simple script mov
difference=targetx-_parent._x;
rate=difference/_basaRate*bounce;
_parent._x+=rate;

targetx (MC destination)is generated randomly at random intervals


I have added collision detection so they will not obscure...but I want the colision to work only if the mcs are still or nearly still, rather than them constantly bouncing each other around to change the targetx only if they are actually gonna rest under another object

I tried using many things the best of which was
if(targetx==_parent._x){
//change destination of mc
}
but the mcs are moving so slow sometimes they are obscured for a long time before the condition is met

can I detect the velocity of the movement? and control the colision with this?
or am I making this very complicated?

any pointers ....muchly appreciated...

Trouble With Velocity And Friction
I'm creating a swf that I want to mimic a drawer coming in and out of a cabinet. What I'm trying to do is add velocity to the drawer with friction. I want the drawer to stop at certain points, as drawers tend to do, but when I add the velocity and friction, the stop points are ignored unless you hold down on the mc while moving it. I know the problem lies somewhere in the code telling the drawer_mc how far to move and determine left and right, but I am too dimwitted to figure this out. Any suggestions would be greatly appreciated.Code:

init();
dragging = false;
friction = 0.98;
top=0;
bottom=0;
vx = Math.random() * 10-5;
vy = Math.random() * 10-5;

drawer.onPress = function()
{
   oldX = drawer._x;
   oldY = drawer._y;
   dragging = true;
   drawer.startDrag(lockCenter, 175.7, 105.6, 420.8, 105.6);
};

drawer.onRelease = function()
{
   dragging = false;
   drawer.stopDrag();
};

drawer.onReleaseOutside = function()
{
   dragging = false;
   drawer.stopDrag();
};

function onEnterFrame(Void):Void
{
   if (!dragging)
   {
      vx *= friction;
      vy *= friction;
      drawer._x += vx;
      drawer._y += vy;
      if (drawer._x = drawer._width / 2 > right)
      {
         drawer._x = right - drawer._width / 2;
      }
         else if (drawer._x - drawer._width / 2 < left)
      {
         drawer._x = left + drawer._width / 2;
      }
   }
   else
   {
      vx = drawer._x - oldX;
      vy = drawer._y - oldY;
      oldX = drawer._x;
      oldY = drawer._y;
   }
}

Difference Between Flash 4/5 - Velocity Of Objects?
Hi,

I'm reposting this question because inisially i didn't know what was wrong with why my MC wasn't working, but now i've realized the problem... i think it is some differece in the publishing of flash 4 to 5. I've found this tutorial on flashkit

http://www.flashkit.com/movies/Games...-446/index.php

it is a way to make objects move and bounce off each others and boundries. It only works when i publish it in flash 4 and not in 5. I want to use this effect, but i need to publish in flash 5 for some other code i'm using.

If any of you could help me i'd be soooo appreciative. while I have an understanding of AS, i'm really a designer and can't do extensive coding.

here is the code that perhaps is causing the problems if someone knows this is ok that would be helpful too becasue perhaps it is something else, its driving me crazy!!:

// ----------------------------------------------
// start move
// ----------------------------------------------
my_radius = (getProperty("", _width)/2);
// 'n' is always 'name' of circle.
my_x = getProperty("", _x);
my_y = getProperty("", _y);
my_n = getProperty("", _name);
if (Number(ymov) == Number("")) {
// *********************************
// ----------------------------------------------
// first run through code,
// this will initialize circle
// ----------------------------------------------
// *********************************
// pick a distance:
ymov = Number(random(/:speed))+1;
xmov = Number(random(/:speed))+1;
//
// pick a direction:
ysign = random(2)-1;
if (Number(ysign) == 0) {
ysign = 1;
}
xsign = random(2)-1;
if (Number(xsign) == 0) {
xsign = 1;
}
// adjust x and y movement
xmov = xmov*xsign;
ymov = ymov*ysign;
// ----------------------------------------------
}
// *********************************
// ----------------------------------------------
// check edges
// ----------------------------------------------
if (Number(my_x)<=Number(Number(my_radius)+Number(/:speed))) {
xmov = xmov*-1;
my_x = Number(my_radius)+Number(/:speed);
}
if (Number(my_y)<=Number(Number(my_radius)+Number(/:speed))) {
ymov = ymov*-1;
my_y = Number(my_radius)+Number(/:speed);
}
if (Number(my_x)>=Number(/:movie_width-my_radius-/:speed)) {
xmov = xmov*-1;
my_x = /:movie_width-my_radius-/:speed;
}
if (Number(my_y)>=Number(/:movie_height-my_radius-/:speed)) {
ymov = ymov*-1;
my_y = /:movie_height-my_radius-/:speed;
}
// ----------------------------------------------
// check for collision
// ----------------------------------------------
n = 1;
// start checking for collisions
while (Number(n)<=Number(/:total_circles)) {
// don't check myself
if (n ne my_n) {
n_x = getProperty("../" add n,_x);
n_y = getProperty("../" add n,_y);
n_radius = (getProperty ("../" add n, _width) / 2);
delta_x = (Number(my_x)+Number(xmov))-(n_x);
delta_y = (Number(my_y)+Number(ymov))-(n_y);
if (Number((Number(delta_x*delta_x)+Number(delta_y*de lta_y)))<Number(((Number(my_radius)+Number(n_radiu s))*(Number(my_radius)+Number(n_radius))))) {
// ----------------------------------------------
// handle collisions
// ----------------------------------------------
// I collided with circle 'n'.
nx = eval("../" add n add ":xmov");
ny = eval("../" add n add ":ymov");
// swap travel values with it.
tempx = xmov;
xmov = nx;
set ("../" add n add ":xmov", tempx);
tempy = ymov;
ymov = ny;
set ("../" add n add ":ymov", tempy);
set ("../" add n add ":collision", my_n);
} else {
}
}
n = Number(n)+1;
}
// ----------------------------------------------
// move me
// ----------------------------------------------
setProperty ("", _x, Number(my_x)+Number(xmov));
setProperty ("", _y, Number(my_y)+Number(ymov));
// ----------------------------------------------

Basic Velocity Script Problem
Hi, I'm having trouble setting the variables of an instantiated object!

The following is ALL the code in my instantiated object:

onClipEvent(enterFrame) {
if (this._x < 600)
this._x += scaleSet;
}


Elseware in my code I have an on (release) with the following

bcount++;
duplicateMovieClip(_root.ball, "ball" + bcount, bcount);
setProperty("_root.ball"+bcount, _x, this._x);
setProperty("_root.ball"+bcount, _y, this._y);

Everything is going great from here, but I NEED to set the velocity of the instance. The variable that needs to get set is "scaleSet".

The following code illustrates a static version of what I want:

_root.ball1.scaleSet = 15;
_root.ball2.scaleSet = 8;
_root.ball3.scaleSet = x;

You get the idea... But the problem is I can't explicitly call ball1, ball2 etc. because I have no clue how many instances will be used.

I've tried things like ("_root.ball" + bcount).scaleSet = 15;
and although it won't error, it won't work either.

Please let me know guys, THANKS!
Iconoclast

Sync Repeating Sound With Mc Velocity
I'm working on a project that incorporates an mc that looks like a big "Wheel of Fortune" prize wheel. You can click/drag to rotate the wheel. My goal is to hook this rotation up to a sound file (single click sound) that syncs/corresponds to the speed of rotation, so that when you grab and move it quickly, the clicks repeat at a fast rate, and as it slows down, the clicks slow with the wheel speed until eventually they stop when the wheel stops.

Any ideas on how to execute greatly appreciated!

Velocity And Veriable Frame Rates
Hi All

I have a sticky math question

I have to get an object to a specific point over a specific distance from an initial velocity (Vo) to 0 (Vf).

I have to guarentee the time it takes to get to that point regardless of the frame rate.

I got it to work if the frame rate is constant but I don't have a clue how to do it is the framerate varies. I calculate the true frame rate (I get to about 1.3*24 fps)

this.accl = (0-this.Vo)/(this.TimeFrms);
// Update velocity
this.Vo += this.accl;
// move object
_root.object._x += Vo;
//
this.TimeFrms -= 1; // This is where the problem is. If the time since the last call is not 1 but 1.3 then it falls over.

Hope someone can help

Thanks a lot for looking at the problem

Buttons To Change Video Velocity
Hi Everybody i would like to know if it´s posible to create a button to change the speed of a video in flash, because i have several videos showing how to play the guitar and sometimes is too fast for begginers .
Regards.
MArcos

Moving Timeline (in Two Velocity Steps)
Hallo Dear Flash-Tutor!
There is a beautiful timeline in a also very nice website created by Terra Incognita with the help of Branden Hall : http://www.mnh.si.edu/africanvoices/

In the following pages on this site there is a moving timeline which i find very great.
See in the meta-chapter "History" - then in the smaller chapters in the green line:
for example "Mali" or "Ethiopia", etc. In this sub-chapters appears the Timeline i am looking for.
When you go with the mouse to the end of the timeline window, the timeline is starting moving, and this the more quicker, the more you come to the edge of the timeline-window.
I would be very grateful for someone to help me in finding the script of this kind of timeline. May it be possible to ask or fwd my request to Branden Hall, as he will know. Thank You so much for your help!!!!

Good Bye,
Ulrich

Dynamicly Changing Velocity By User Input
here is a simple code for velocity, how do i change this so the user can specify what velocity the box goes at through either an input box or a slider scale thingy?


Code:

onClipEvent (load) {

// velocity of object along the x-axis
x_velocity = 5;

// timestep (no. of frames)
fps = 24;
time = fps/60;

//set a variable for distance travelled
x_distance = (x_velocity*time);

}
onClipEvent (enterFrame) {

// change the position of the object due to the velocity
this._x += x_distance*(time);

// add an if clause so the animation loops back
if (_x>300) {
_x = 0;
}else if (_x<-26){
_x = 301;
}
}
:] ideas anyone?

HitTest/velocity Problems On Rising Menu...
Hello,

I have a rising menu that when you roll your mouse over it, it rises and when you move your mouse away, it falls back down.

I can't seem to get the HitTest right on this menu. The problem is that when I preview the menu, the menu falls down and then waits for the user to select it (I'd rather the menu look static until the user selects the menu). Then, the menu shakes up and down if you happen to select the bottom box of the menu. I'm not sure how to fix that.. Can you help me? I think the problem may have to do with the HitTest or the velocity/fukx code?

This the code right now:


Code:
onClipEvent (load) {
_root.newx = 145
vel = 3
}
onClipEvent (enterFrame) {


if(this.hitTest(_root._xmouse,_root._ymouse,true)) _root.newx = -1;
else _root.newx = 145;



fukx += (_root.newx-_y)/vel
_y = Math.round(fukx);




}


I'll attach my file to this posting... Thanks!

'tweening' With Taking Initial Velocity Into Consideration
Hi, I've been developing this little navigation system where the links are organized in a stack and the stack behavior is a bit complex, just to make it attractive...
now, animation is controled from within actionscript ofcourse.
what I wanted is for the animated elements to be able to change final destinations while within their trajectories in a realistic ways. Unlike all the 'tweening' demos that I've seen on the net, none of them take into account the initial velocity of an object and calculate the acceleration accordingly. As a result when final points are changed objects act as though they have no inertia and just suddenly change the vector of their path... this is not realistic...

so, using simple formulas for average speed [(V_final + V_initial)/2] and acceleration [(V_final - V_initial)/t] i derived a formula where acceleration is calculated using initial speed and delta_X which is (x_final - x_initial)...
formula is
(2*(delta_X - V_initial*t)) / t^2

now this formula gives me the results I want. I precalculate the speed for every time intervals and store it all in an array so that when the animation loop is run there is only an addition to be done (of speed to the X variable of the clip). This saves me time so that I can animate more objects on screen at the same time without the drop in framerate.

the problem is that the clip overshoots always and if I dont let it come to a full stop before I give it a new final destination (by clicking elsewhere) it starts overshooting in an increasing manner ( subsequent clicks make the clip overshoot more and more - calculation error is being added and added)

the formula is good as it is continuous. to problem is in the discrete nature of the simulation...

hope that there is someone willing to look at it and maybe give me some suggestions.

this is the main animation code of the whole project so the minor imperfection in it is really giving me trouble when I try to go to sleep.

code will run as is, ofcourse you have to add the symbol and link it properly, but you know this already.

THANK YOU VERY MUCH.
HELP IS APPRECIATED!

/////////////////////////////////////////////////////////////////////
//IVAN TRAJKOVIC, NEW YORK, WASHINGTON HEIGHTS, TUESDAY MARCH 15 2005
/////////////////////////////////////////////////////////////////////

//================================================== ==========================

maxSimulationFPS = 30;
totalSimulationTime = 1;//time in seconds for the simulation to last

ball_mc.initialX = null;
ball_mc.finalX= null;
ball_mc.initialY = null;
ball_mc.finalY= null;

ball_mc.velocityX = 0;
ball_mc.velocityY = 0;

ball_mc.accelerationX= null;
ball_mc.accelerationY = null;

ball_mc.decelerationX = null;
ball_mc.decelerationY = null;

ball_mc.decelerationPoint= 3/4;//fraction of the total position change where the deceleration begins

ball_mc.currentInterval= null;//indicates which interval of the simulation the function is in

//================================================== ==========================

/*ACCELERATION CALCULATIONS USE THE ACCELERATION(UNIFORM) FORMULA:
2*(deltaX - V_initial*deltaT)/deltaT^2*/

/*DECELERATION CALCULATIONS USE THE ACCELERATION (WITH INITIAL AND FINAL SPEEDS) FORMULA:
(V_final - V_initial) / deltaT*/

/*FINAL VELOCITY CALCULATIONS USE THE FORMULA:
(2*deltaX - deltaT*V_initial)/deltaT*/

////////////////////////
function simulationSetup()
////////////////////////
{
//VARIABLES----------------------
var accelerationSegmentDeltaX = null;
var accelerationSegmentDeltaY= null;

var velocityXAtStartOfDecelerationSegment = null;
var velocityYAtStartOfDecelerationSegment = null;
//-------------------------------

ball_mc.currentInterval = 0;

ball_mc.initialX = ball_mc._x;
ball_mc.initialY = ball_mc._y;

//CALCULATES THE DISTANCE FROM THE START WHERE THE ACCELERATION STOPS------
accelerationSegmentDeltaX = ( ball_mc.finalX - ball_mc.initialX ) * ball_mc.decelerationPoint;
accelerationSegmentDeltaY= ( ball_mc.finalY - ball_mc.initialY ) * ball_mc.decelerationPoint;
//-------------------------------------------------------------------------

//FIRST PART OF THE PATH WHERE ACCELERATING------------
ball_mc.accelerationX = 2 * ( accelerationSegmentDeltaX -
ball_mc.velocityX *
totalIntervalsInSimulation * ball_mc.decelerationPoint ) /
Math.pow( totalIntervalsInSimulation * ball_mc.decelerationPoint , 2);

ball_mc.accelerationY = 2 * ( accelerationSegmentDeltaY -
ball_mc.velocityY *
totalIntervalsInSimulation * ball_mc.decelerationPoint ) /
Math.pow( totalIntervalsInSimulation * ball_mc.decelerationPoint , 2);
trace("ball_mc.accelerationY: " + ball_mc.accelerationY);
//-----------------------------------------------------

//CALCULATES THE VELOCITY AT THE START OF THE DECELERATION SEGMENT---------
velocityXAtStartOfDecelerationSegment = ( 2 * accelerationSegmentDeltaX -
( ball_mc.decelerationPoint * totalIntervalsInSimulation ) *
ball_mc.velocityX ) /
( ball_mc.decelerationPoint * totalIntervalsInSimulation );

velocityYAtStartOfDecelerationSegment = ( 2 * accelerationSegmentDeltaY -
( ball_mc.decelerationPoint * totalIntervalsInSimulation ) *
ball_mc.velocityY ) /
( ball_mc.decelerationPoint * totalIntervalsInSimulation );
trace("velocityYAtStartOfDecelerationSegment: " + velocityYAtStartOfDecelerationSegment);
//-------------------------------------------------------------------------

//SECOND PART OF THE PATH WHERE DECELERATING-----------
//'0' - is the speed at the end of deceleration - OBJECT COMES TO A COMPLETE STOP!
ball_mc.decelerationX = (0 - velocityXAtStartOfDecelerationSegment) / (totalIntervalsInSimulation * (1 - ball_mc.decelerationPoint));

ball_mc.decelerationY = (0 - velocityYAtStartOfDecelerationSegment) / (totalIntervalsInSimulation * (1 - ball_mc.decelerationPoint));
trace("ball_mc.decelerationY: " + ball_mc.decelerationY);
//-----------------------------------------------------
}

//================================================== ==========================

decelerationPointInterval = null;//interval index where acceleration turns into deceleration (here for efficiency reasons)
totalIntervalsInSimulation = null;

totalIntervalsInSimulation = maxSimulationFPS * totalSimulationTime;
decelerationPointInterval = totalIntervalsInSimulation * ball_mc.decelerationPoint;
//decelerationPointInterval = 22;
trace("decelerationPointInterval: " + decelerationPointInterval);
//================================================== ==========================

/////////////////
function moveBall()
/////////////////
{
//at the end of the simulation reinitialize all simulation-relevant variables so that object is ready for next simulation
if (ball_mc.currentInterval > totalIntervalsInSimulation)
{
ball_mc.currentInterval = 0;

ball_mc.initialX = ball_mc._x;
ball_mc.initialY= ball_mc._y;

ball_mc.velocityX = 0;
ball_mc.velocityY= 0;

clearInterval(intervalIdentifier);
intervalIdentifier = null;

return;
}

if (ball_mc.currentInterval == 0)
{
ball_mc.currentInterval++;
return;
}

if (ball_mc.currentInterval < decelerationPointInterval)
{
ball_mc.velocityX += ball_mc.accelerationX;
ball_mc.velocityY += ball_mc.accelerationY;
}
else
{
ball_mc.velocityX += ball_mc.decelerationX;
ball_mc.velocityY += ball_mc.decelerationY;
}

ball_mc._x += ball_mc.velocityX;
ball_mc._y += ball_mc.velocityY;

ball_mc.currentInterval++;
}

//================================================== ==========================

////////////////////////////
_root.onMouseDown = function()
////////////////////////////
{
ball_mc.finalX = this._xmouse;
ball_mc.finalY = this._ymouse;

trace("ball_mc._y: " + ball_mc._y);
trace("ball_mc.finalY: " + ball_mc.finalY);

simulationSetup();

//STARTS THE SIMULATION
if (intervalIdentifier == null)
{
intervalIdentifier = setInterval(moveBall, 1000/maxSimulationFPS);//1000ms == 1s. to see how many times per second should it execute
}
}

HitTest/velocity Problems On Rising Menu...
Hello,

I have a rising menu that when you roll your mouse over it, it rises and when you move your mouse away, it falls back down. (Thanks to Senocular's code!)

Unfortunately, the problem I have is that if the menu rises and you happen to put your mouse near the bottom of the menu, the menu will be very touchy, rising and falling until you move it away.

I was wondering if the menu could be triggered to go down only if you rollover the same menu again. Or, that when you rolloff, it has to complete the rolloff before starting over? Is this the only way this problem could be solved?

This is the code:

Code:
//elastic function (created by Senocular)
MovieClip.prototype.elasticMove = function(targt, accel, friction) {
this.speed += (targt - this._y) * accel;
this.speed *= friction;
this._y += this.speed;
}
var origY = menuItem1InstanceName._y
menuItem1InstanceName.onEnterFrame = function() {
if (this.hitTest(_root._xmouse, _root._ymouse, true)){
this.elasticMove(positionToSpringTo, .5, .6);
} else {
this.elasticMovie(origY, .5, .6);
}
};
I'll attach my file to this posting... Thanks!

Can Flash Detect Realtime Audio Data? (for Linking Visuals To Audio Velocity, Etc)
I've seen a lot of Oscilloscopes for Flash but they've all been fake - they simply generate random patterns that look convincing, expecially if the sound is erratic and would produce chaotic oscilloscope feedback anyway, but they actually have no connection whatsoever to the sounds that are playing.

I've heard people claim however that real oscilloscopes can actually be made in Flash, and I was wondering if anyone could point me towards some resources for looking into it.

I have a distinct feeling that they are probably misguided or just plain incorrect anyway, but it's still a prospect that interests me a lot.

Much thanks,
pH

Movie Clip Mouse Speed Control Depending On Mouse Press
Hi,
Please help me !
As iam developing a small ball game in flash, where i need to control the speed of the ball (i.e, to increase or decrease the speed of ball)when clicked on a button depending on mouse press .

I have done similar on key press but iam not able to do the same for mouse pressed.


Please help me out

Your help will be appreciated.

Thanks & Regards
Zabi

OnPress Doesn't Work If The Mouse Button Is Pressed Again But The Mouse Is Not Moved.
I have a very simple piece of code but it has one very annoying bug. When I press the button a second time, the code doesn't work. The only way to get the code to work is by moving the mouse a tiny bit, or moving the mouse off the button and back on.

Does anyone know a way to make a button that can be clicked many times without moving the mouse?


Code:
randommultiquiz.onPress = randommultiquizOnPress;
function randommultiquizOnPress() {
_root.attachMovie("connect", "newconnect", 200);
newconnect._x = 0;
newconnect._y = 0;
newconnect._xscale = 100;
newconnect._yscale = 100;
}

How Do I Create A Movieclip To Play If Mouse Is Unactive, And Stops When Mouse Moves?
I am in the process of creting a world map navigation for a global ite portal.

In the map a user can hover over different continents to zoom in on specific countries then click on that country's to goto its specific website.

However I think the world map looks a little un-user friendly so was looking at playing a quick tutorial movie (a mouse cursor, moving over a continent and highlighting it) when the mouse is not being moved, then stops when the user moves the mouse.

This feature a little reminisant of when sonic the hedgehog used to tap his foot if you didnt use your joypad for a while.

I would also like to start the movie (after he preloader ive used) with the tutorial playing, so the user can understand the way it works straight away.

I am a novice at action scripting, so all help would be appreciated!

Thanks

M

How Do I Create A Movieclip To Play If Mouse Is Unactive, And Stops When Mouse Moves?
I am in the process of creting a world map navigation for a global ite portal.

In the map a user can hover over different continents to zoom in on specific countries then click on that country's to goto its specific website.

However I think the world map looks a little un-user friendly so was looking at playing a quick tutorial movie (a mouse cursor, moving over a continent and highlighting it) when the mouse is not being moved, then stops when the user moves the mouse.

This feature a little reminisant of when sonic the hedgehog used to tap his foot if you didnt use your joypad for a while.

I would also like to start the movie (after he preloader ive used) with the tutorial playing, so the user can understand the way it works straight away.

I am a novice at action scripting, so all help would be appreciated!

Thanks

M

How Do I Create?: Scrolling Image Stops On Mouse Over-starts On Mouse Off
I’m trying to create this animation:

I have an long rectangular image (with more images going across it) scrolling FROM the right side of the screen to the left (very slowly). similar to a ticker.

I want the scrolling to stop when the viewer mouses over the menu strip. If they press on the image that they have just moused over, I have a movie clip I want to play for that image (a few images pop up, one bigger than the other). When the viewer mouses off, the movie clip disappears, and the menu continues scrolling to the left, from the right.

Greatly appreciated!!

Playing A Movie Clip On Mouse Over And Continue To Last Frame On Mouse Out
Hi All,

I have a movie clip on the timeline which is an animated mouseover button

Basically what I need to do is for the movie to be stopped at frame one when there is no mouse over and loop continuosly when I do have mouse over then on mouse out i want it to finish it's frames playing from where ever it was at when the mouse was moved out to the last frame and then display frame one so it is stopped again ready for a new mouse over.

Something I have found difficult to work out is that whilst it is doing the "out" play to to last frame, if you put the mouse back over again, it starts from frame 1 so looks like it jumps so i need the mouse over to also read what frame it is currently playing so that it can continue its endless loop from that frame to avoid it jumping about.

I hope that makes sense, it's really difficult to describe in words.

Here's the movie clip's action as it is now.

on (rollOver)
{
this.gotoAndPlay("over");
}
on (releaseOutside, rollOut)
{
this.gotoAndPlay("out");
}

ok so in the movie's timeline itself, the label "over" is a frame containing another movieclip which is basically a continous 30 frame loop and my movie timeline is stop();

so, on (rollOut) it plays at label "out"

I have placed a copy of the movie loop at the "out" frame which plays the movie slower at the end to make it a nice wind down stop

what I thought to do in action script is to read the current frame that the movie loop is at and make so the "out" position movie starts its playing frame from that frame number until it reaches the end frame where it jumps back to frame one of the timeline with the first stopped frame.

I've seen a command something like this below used to get the current frame number and take it away from the total to continue playing from that point, that's not totally right for what I am doing but it shows me the sort of thing i need to write but i don't know how to write an actionscript to read the current frame from the movie1 whcih is playing and start playing movie2 at "out" from that frame number?

on (rollOut) {gotoandPlay(_totalframes - _currentframe); }

maybe there is an easier way to get this to work, i've seen lots of similar examples on the web but nothing that specifically plays a lopp and then continues to the end on mouse out. it sounds simple but I've tried all weekend to do it without success?

Can anyone help me please?

Thanks,
Terrence.

Mouse Follow/stopfollow After Mouse Leaves Object (with Ease)
well, i think the title covers me entirely, i would like some help with a script.
The problem is, i have a scene with objects that at first they are static, when the mouse comes in and makes a move-over the scene and some objects,i have assigned multiple collision to the objects, i want when the mouse moves over a object, the object to follow the mouse,while colliding to all other objects and after a while i would like as the mouse moves away, the following to stop and the objects to return to its original spot with ease.

I know that this is a big one, but i would like some help if i could get

Detect Mouse _x & _y Attach Specific Clip And Have It Follow Mouse
I'm trying to make a clip that will have another clip attached (eventually it'll be a mask) when you roll over it. I want the mouse positon to be determined on rollover and a different clip (with different registration point) to be attached depending on which quadrant you rollover first. IE- you rollover the lower left quadrant of the mc first so an mc with an upper right registration point is attached and follows the mouse.

basically I want it to look like you're pulling a mask from out of nowhere onto the main mc from whatever corner you start on... (make sense?)

i'm trying to reconstruct what you see here (http://www.mullerphoto.com/)
this is the first baby step!

anyhow, here's my AS and i'll attach the .fla any help is great! I have the actionscript dictionary and am not afraid to use it, I just need help with the mechanics of how to actually do this (i.e.- which methods, properties, etc. to utilize) thanks!


Code:
leftfunction = function(){
if (patch._ymouse <= 100){
llowerfunction;
}else{
//this function starts the maskclip coming in from the upper left with a lower right reg point
_root.patch.attachMovie("lowerright", "lrclip", 1);
lrclip._x = _root.patch._xmouse;
lrclip._y = _root.patch._ymouse;
}
}

llowerfunction = function(){
//this function starts the maskclip coming in from the lower left with an upper right reg point
patch.attachMovie("upperright", "urclip", 1);
urclip._x = patch._xmouse;
urclip._y = patch._ymouse;
}

rightfunction = function(){
if (patch._ymouse <= 100){
rlowerfunction;
}else{
//this function starts the maskclip coming in from the upper right with a lower left reg point
patch.attachMovie("lowerleft", "llclip", 1);
llclip._x = patch._xmouse;
llclip._y = patch._ymouse;
}
}

rlowerfunction = function(){
//this function starts the maskclip coming in from the lower right with an upper left reg point
patch.attachMovie("upperleft", "ulclip", 1);
ulclip._x = patch._xmouse;
ulclip._y = patch._ymouse;
}

_root.patch.onRollOver = function() {
if (patch._xmouse <= 150){
leftfunction;
}else{
rightfunction;
}}

Custom Mouse Cursor Conflict With Mouse Trail
When I put mouse trails and custom mouse cursor script in the same scene the mouse trails work but the cursor does not change to the custom cursor. If I use the custom mouse cursor script in a seperate scene, on its own, it works fine. I think that the two scripts are conflicting.
Mouse trail script:

onClipEvent (enterFrame) {
//x movement
mx=_root._xmouse;
if (mx<_x) {
dx=_x-mx;
}
else {
dx=mx-_x;
}
moveSpeedx=dx/10;
if (mx<_x) {
_x=_x-moveSpeedx;
}
else {
_x=_x+moveSpeedx;
}
//y movement
my=_root._ymouse;
if (my<_y) {
dy=_y-my;
}
else {
dy=my-_y;
}
moveSpeedy=dy/10;
if (my<_y) {
_y=_y-moveSpeedy;
}
else {
_y=_y+moveSpeedy;
}
}

Custom mouse cursor script:
Layer 1(functions):

stop();
/* update the cursor coords */
function updateCursor() {
_root.cursor._x = _xmouse;
_root.cursor._y = _ymouse;
updateAfterEvent();
}

Layer 2(on event handlers):

onClipEvent(load) {
Mouse.hide();
this.swapDepths(100);
}
onClipEvent(mouseMove) {
_root.updateCursor();
}

Please help!

Mouse Direction Scroll With Mouse Over Image Enlargement...
Hi all..

Haven't had much luck finding a tutorial to help me do this one so any help locating it would be good.. I'm trying to design an image gallery where the images scroll left to right depending on mouse movement. Once a mouse is over an image it enlarges then returns to normal shape with mouse off.

any help appreciated..

cheers!

Mouse Over, MC Scales Up, Mouse Out, MC Returns To Original Size...
I have looked around and I cannot find a simple script to apply to a clip that does this...

On Mouse over - MC scales up, on Mouse out, MC returns to original size... with some easing.

Please help!!

Scroller That Moves According To Mouse Movement Not Mouse Location.
I am trying to recreate the effect seen here:

Express Top Ten

alright here's the request:

I have found many scroller tutes most of which use buttons to control them. What I need or think I need is a tute or file to refer to, that uses a mouseover effect to move the movieclip with respect to how much the mouse has moved and still uses easing.

I have found files that make the movieclip move according to the mouse position on the stage, but i need it to move in according to how far it just moved.

feel free to email me with any questions.

thanks in advance,
chris
email me

Changing Mouse Cursor On Mouse Over/out Without Drag Movie?
Hello,
I have a movie clip/button that activates some actions but I don't want the mouse pointer show the link icon (hand) and instead show the normal arrow icon. Is this possible with a fast mouse.smth actionscript or is a complex startdrag/stopdrag of movieclips the only way out? Thanks in advance.

Mouse Hittest Too Slow? Mouse Passes Over Wall
Hi everyone,

I'm having a problem with a new game i'm working on.

I have the following code to attach a movieclip to the mouse:


Code:
startDrag(_root.dot, true)
Mouse.hide();


Ok, and i have a wall movieclip with the following:


Code:
if (_root.dot.hitTest(_root.wall)){
trace("hit!")
}



This works fine, as long as you move the mouse slowly -- if you zip it over the wall, it seems that the hittest doesnt have time to register the hit? Or that the "_root.ball" doesnt actually go over the wall, it just is transported to the new mouse location? (im not sure )

Any infomation on how to make the hittest 100% detect the mouse over the wall would be great.

Many thanks.

Regards.

[F8] Follow The Mouse - Stop Mc At Location Of Mouse On Click
I have an mc that follows the mouse a certain distance on the x in both directions and then eases to a stop when the mouse gets a certain distance.

What I need to do is to have the mc stop on button click at the x position it is at on click. Then, when another button is clicked the animation continues from it's stopped location to the new mouse location. All with easing of course.

Here is the code for the mouse tracking:

Code:
onClipEvent (load) {
speed = 3;
}
onClipEvent (load) {
stageWidth = 700;
imageWidth = 615;
}
onClipEvent (enterFrame) {
destx = (stageWidth-imageWidth)*(_root._xmouse/stageWidth)
_x += (destx-_x )/speed;
}

Any help would be greatly appreciated.

Copyright © 2005-08 www.BigResource.com, All rights reserved