Convert simple Flash AS2 code to AS3
I'm a Flash beginner and followed a tutorial: http://www.webwasp.co.uk/tutorials/018/tutorial.php ... to learn how to make a "live paint/draw" effect. I didn't realize that if I made something in AS2, I wouldn't be able to embed it (and have it work) into my root AS3 file, where I've got a bunch of other stuff going on. I've tried following tips on how to change AS2 code to AS3, but it just doesn't work. I know it's simple code, and that some genius out there can figure it out, but I'm at a loss. Please help!
Here's the AS2 code:
_root.createEmptyMovieClip(开发者_StackOverflow中文版"myLine", 0);
_root.onMouseDown = function() {
myLine.moveTo(_xmouse, _ymouse);
ranWidth = Math.round((Math.random() * 10)+2);
myLine.lineStyle(ranWidth, 0xff0000, 100);
_root.onMouseMove = function() {
myLine.lineTo(_xmouse, _ymouse);
}
}
_root.onMouseUp = function() {
_root.onMouseMove = noLine;
}
Here is the exact same thing in AS3
import flash.display.Sprite;
import flash.events.MouseEvent;
var ranWidth:Number;
//creation of a new clip (Sprite is the base class of MovieClip,
//it's the same without the unneeded timeline)
var myLine:Sprite = new Sprite();
addChild(myLine);
//in AS3 the main container is stage, not _root
//you see here the main difference between beginner AS3 and beginner AS2:
//event listeners
stage.addEventListener(MouseEvent.MOUSE_DOWN, onMouseDown);
function onMouseDown(event:MouseEvent):void
{
myLine.graphics.moveTo(mouseX, mouseY);
ranWidth = Math.round((Math.random() * 10)+2);
myLine.graphics.lineStyle(ranWidth, 0xff0000, 100);
stage.addEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
stage.addEventListener(MouseEvent.MOUSE_UP, onMouseUp);
}
//nesting function in other functions is not a good practice
function onMouseMove(event:MouseEvent):void
{
myLine.graphics.lineTo(mouseX, mouseY);
}
function onMouseUp(event:MouseEvent):void
{
stage.removeEventListener(MouseEvent.MOUSE_MOVE, onMouseMove);
stage.removeEventListener(MouseEvent.MOUSE_UP, onMouseUp);
}
精彩评论