Search code examples
flashactionscriptadobe

Actionscript 3 rotate object to mouse


Hello i watched tut on youtube and i wrote this code to make object rotate to mouse position, but it kinda doesnt work correctly.

code:

package  {

import flash.display.MovieClip;
import flash.events.Event;

public class char extends MovieClip
{
    private var _pointer = this;

    public function char()
    {
        addEventListener(Event.ENTER_FRAME, onEnter);
    }

    private function onEnter(event:Event):void
    {
        //Initialize dx and dy variables
        var dx:Number = mouseX - _pointer.x;
        var dy:Number = mouseY - _pointer.y;

        //Store angle in angle variable
        var angle:Number = Math.atan2(dy, dx) * 180 / Math.PI;

        //Apply angle
        _pointer.rotation = angle;
    }
}

}


Solution

  • You need to take mouseX and mouseY coordinates from the parent movie clip because:

    1. _pointer.x and _pointer.y are also expressed in the parent's coordinate system
    2. Rotation of a movie will interfere with mouseX and mouseY values (they will reflect the non-rotated object)

    So you need to modify these two lines:

    var dx:Number = parent.mouseX-_pointer.x;
    var dy:Number = parent.mouseY-_pointer.y;