PDA

View Full Version : how to calculate mouse's distance to a certain point



emrsag
December 4th, 2009, 10:02 PM
Hello,
What I am trying to do with AS3 in Flash cs4 is calculate the cursor's distance to given point (let say 400,300) and use that distance to constantly (20 fps) change my curtain's alpha value. (which is basically a box turned into a movie clip)

I'm very new to AS3 environment, so I could have been doing lots of mistakes but here is my code.


function where(event:Event) {
xval=mouseX;
yval=mouseY;
}

state.addEventListener(Event.EXIT_FRAME, where);

//I need to check which value is bigger since i dont know how to use absolute value function in AS3.

if (xval>=400) {
distancex=xval-400;
} else {
distancex=400-xval;
}

if (yval>=300) {
distancey=yval-300;
} else {
distancey=300-yval;
}

distancet=distancex+distancey;

//I want to show the items behind my curtain if the cursor is very close to my point, so if the distance is more than 400, aplha will be stayed as 1 and will not show what's behind.

if (mesafet<400) {
mesafea=mesafet/400;
} else {
mesafea=1;
}

function update(event:Event):void {
perde.alpha=mesafea;
}

stage.addEventListener(Event.ENTER_FRAME, update);

emrsag
December 4th, 2009, 10:03 PM
btw it isn't working properly. I already thank a lot to who'll help.

raghu_thejus
December 5th, 2009, 03:34 AM
try using Event.MOUSE_LEAVE listener.i think tat wil work..

emrsag
December 5th, 2009, 07:17 PM
oh, ty

the working code is;


function nerede(event:Event) {
xval=mouseX;
yval=mouseY;

if (xval>=400) {
mesafex=xval-400;
} else {
mesafex=400-xval;
}

if (yval>=300) {
mesafey=yval-300;
} else {
mesafey=300-yval;
}

mesafet=mesafex+mesafey;

if (mesafet<200) {
mesafea=mesafet/200;
} else {
mesafea=1;
}
}

stage.addEventListener(Event.ENTER_FRAME, nerede);



function update(event:Event):void {
perde.alpha=mesafea;
}

stage.addEventListener(Event.ENTER_FRAME, update);

lewi-p
December 7th, 2009, 05:01 AM
Hi,

Try this: All you need to do is create a MovieClip, drag it on the stage (to x:400, y:300 - for the purpose of this demo) and give it an instance name 'box_mc'.


var point:Point = new Point(400, 300);

this.addEventListener(Event.ENTER_FRAME, checkDistance);

function checkDistance(e:Event):void
{
var dx:Number;
var dy:Number;
var alph:Number;

if (mouseX > point.x) dx = point.x - mouseX;
else dx = mouseX - point.x;

if (mouseY > point.y) dy = point.y - mouseY;
else dy = mouseY - point.y;

alph = (dx + dy) / (point.x + point.y) + 1;

box_mc.alpha = alph;
}

lewi-p

jloa
December 7th, 2009, 05:09 AM
var destination:Point = new Point(0, 0);

stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMoveHandler);

function onMouseMoveHandler(event:MouseEvent):void
{
var mouseLoc:Point = new Point(stage.mouseX, stage.mouseY);
trace(Point.distance(destination, mouseLoc))
}
Let the FP API calculate the distance for you :}