Anyone have any code that will enable the user to rotate a display object (such as a Movieclip)?
I mean, I know how to rotate the object myself, with code, but I need code that will enable the user to have the ability to use their mouse to rotate something like a square or triangle.
First you need to put your shape into an empty container sprite so its center point equals the top-left of the container. This will make your shape rotate around its center.
Afterwards add a MOUSE_DOWN event listener to your shape. Inside its callback function get the current x position of your mouse pointer and store it in a variable.
Finally add a MOUSE_MOVE event to the stage and update the rotation of your shape depending on the difference between your mouse’s initial and the current x position.
Here’s some code:
package;
import openfl.display.Sprite;
import openfl.Lib;
import openfl.display.Sprite;
import openfl.display.Shape;
import openfl.events.MouseEvent;
class Main extends Sprite
{
private var square:Sprite = new Sprite();
private var xPos:Float;
private var oldRotation:Float;
private var mouseDown:Bool = false;
public function new()
{
super();
var shape:Shape = new Shape();
shape.graphics.beginFill(0xff0000, 1);
shape.graphics.drawRect(0, 0, 100, 100);
shape.graphics.endFill();
square.addChild(shape);
shape.x =-50;
shape.y =-50;
addChild(square);
square.x = square.y = 200;
square.addEventListener(MouseEvent.MOUSE_DOWN, pressed);
stage.addEventListener(MouseEvent.MOUSE_UP, released);
stage.addEventListener(MouseEvent.MOUSE_MOVE, rotate);
}
private function pressed(e:MouseEvent):Void
{
xPos = stage.mouseX;
oldRotation = square.rotation;
mouseDown = true;
}
private function released(e:MouseEvent):Void
{
mouseDown = false;
}
private function rotate(e:MouseEvent):Void
{
if (mouseDown)
{
square.rotation = oldRotation + stage.mouseX - xPos;
}
}
}