Skip to main content
Participant
October 26, 2013
Answered

How to make an object follow the mouseX when clicked on

  • October 26, 2013
  • 1 reply
  • 693 views

How to make an object follow the mouseX when clicked on? Please help.

This topic has been closed for replies.
Correct answer Ned Murphy

You should think it thru - your code doesn't match your very simple explanation of what you said it should do, and it should.... click something and have it follow the mouse. 

A game loop (ENTER_FRAME) could work, but in this case it wastes unnecessary processing if the mouse is not moving.  And in your code example it is not waiting for the click to occur.

Use a MOUSE_MOVE event listener instead of an ENTER_FRAME.  Inside the clicking event handler function is where you should be defining the MOUSE_MOVE listener.  The handler for the MOUSE_MOVE listener is where you assign rock1Cnt.x = mouseX.

public function Main():void {

        rock1Cnt.addEventListener(MouseEvent.CLICK, mouseClickHandler);

 

}

 

private function mouseClickHandler(e:MouseEvent):void {

 

       stage.addEventListener(Event.MOUSE_MOVE, followMouse);                    

}

private function followMouse(e:MouseEvent):void {

       rock1Cnt.x = mouseX

}

1 reply

Ned Murphy
Legend
October 27, 2013

You can assign a MOUSE_MOVE event listener when the object gets clicked and have the event handler for that listener match the object's x and y properties to the mouseX and mouseY properties.

mobile8Author
Participant
October 27, 2013

Thanks

Can you help me a bit more I still don't understand fully. Can you show me an example. Please.