PDA

View Full Version : moving object in a straight line using mouse



Eyenstyn
March 12th, 2008, 03:46 AM
Hi, i have created some code to move an object to a mouse pointer's position. The problem is that it does not travel in a straight line.

I think the problem has to do with the conditions of x and y. I want to calculate the gradient(x/y or (x1-x2)/(y1-y20) or create an incrementation of a set of points that are similar to the gradient to reach the destination...i dont know how to do that tho.



var circle:Sprite = new Sprite;
circle.graphics.lineStyle(1,0x0000FF);
circle.graphics.drawCircle(100,100,50);
circle.graphics.endFill();

var mouseClickCheck:Boolean = false;
var circleX:Number = 0;
var circleY:Number = 0;
stage.addEventListener(MouseEvent.CLICK, handleMouseMove);
addEventListener(Event.ENTER_FRAME, UpdatePosition);

addChild(circle);

function UpdatePosition(event:Event):void
{
if(mouseClickCheck)
{
trace("[circleX] = " + circleX);
trace("[circle.x] = " + circle.x);
if(circle.x <= circleX)
{
circle.x += 100;
if(circle.x > circleX)
{
circle.x = circleX;
}
}
if(circle.x >= circleX)
{
circle.x -= 100;
}
if(circle.y <= circleY)
{
circle.y += 100;
if(circle.y > circleY)
{
circle.y = circleY;
}
}
if(circle.y >= circleY)
{
circle.y -= 100;
}
}

}

function handleMouseMove(event:MouseEvent):void
{
mouseClickCheck = true;

circleX = mouseX;
circleY = mouseY;

var g1:Sprite = new Sprite();
g1.graphics.lineStyle(2,0x0000FF);
g1.graphics.beginFill(0x0000FF);
g1.graphics.drawCircle(mouseX,mouseY,5);
addChild(g1);
}

icio
March 12th, 2008, 10:03 AM
If you are wanting to move the movieclip straight towards the mouse cursor, the best way is determined by whether or not you want it to move at a constant speed.

If you are not so worried about moving at a constant speed you can use easing (though there are others) in the following way:

var dx:Number = mouseX - circle.x;
var dy:Number = mouseY - circle.y;
circle.x += dx*0.08;
circle.y += dy*0.08;

// Equivelantly
circle.x += (mouseX - circle.x)*0.08;
circle.y += (mouseY - circle.y)*0.08
This method moves the circle at fraction (in this case the fraction is 0.08 = 1/12.5) of the way along each axis towards the mouse position.

The other method, where you want to maintain a constant speed, is to use trigonometry. You work out the angle between the mouse and circle and move a certain amount in that direction.

var speed:Number = 10;
var dy:Number = mouseY - circle.y;
var dx:Number = mouseX - circle.x;

var r:Number = speed;
var d_sq:Number = dx*dx+dy*dy;
var a:Number = Math.atan2(dy, dx);
if (dy * dy + dx * dx < speed * speed) {
r = Math.sqrt(d_sq);
}
circle.x += r*Math.cos(a);
circle.y += r*Math.sin(a);

There are a few tutorials on this sort of thing on the kirupa.com main site. Hope that helps :thumb: