PDA

View Full Version : Follow cursor and change direction



skippers
March 30th, 2010, 12:52 PM
How could I get an object to follow the cursor and rotate to change direction as the cursor changes direction?:stormtrooper:

yet2bedefined
March 30th, 2010, 01:46 PM
First make sure your object starts facing right.



//assuming myObj is your obect's instance name

/*Calculates the angle between two points - input the dist between "y", and then "x'*/
myObj.rotation = Math.atan2 (myObj.y - mouseY, myObj.x - mouseX);

//Adds the right amount to the x and y - remember high school trig?
myObj.x -= Math.cos (myObj.rotation) * _speed_you_want_it_to_get_there_;
myObj.y -= Math.sin (myObj.rotation) * _speed_you_want_it_to_get_there_;



Memorize this code - you will not believe how useful it is when making games and such.

yet2bedefined
March 30th, 2010, 01:58 PM
Just noticed - the above code doesn't really turn your object - you need to make some modifications to do that:


myObj.rotation = Math.atan2 (myObj.y - mouseY, myObj.x - mouseX) * (180 / Math.PI) + 180;

myObj.x -= Math.cos ((myObj.rotation - 180) * Math.PI/180) * 2/*or whatever speed you want*/;
myObj.y -= Math.sin ((myObj.rotation - 180) * Math.PI/180) * 2/*or whatever speed you want*/;


Notice though that it gets kind of jerky when the object gets really close. You might want to use some if statements to stop this.

skippers
March 30th, 2010, 03:13 PM
many thanks yet2bedefined.

for me your first post came up with errors. With the second post when opening the flash preview the object would face wherever the cursor was originally but it wouldn't move

yet2bedefined
March 30th, 2010, 03:16 PM
many thanks yet2bedefined.

for me your first post came up with errors. With the second post when opening the flash preview the object would face wherever the cursor was originally but it wouldn't move

You need to add this within a "ENTER_FRAME" event:



stage.addEventListener (Event.ENTER_FRAME, onFrame);

function onFrame (evt:Event):void {
/*code here*/
}

skippers
March 30th, 2010, 03:38 PM
FANTASTIC! thanks

a problem arises when the object leaves the stage and then comes back flashing on and off, or if you leave the cursor on the stage the object will flash from side to side of it.