Flickering rectangle using AS3 and drawRect() when using math for coordinates

104 views Asked by At

I have a strange problem that perhaps someone has also experienced. While using ActionScript 3 and the drawRect() function to create a movie clip on run time, I am experiencing some flickering when trying to use math to determine the position it gets drawn in.

The following code creates a nice, solid rectangle with no issue:

var mc:MovieClip = new MovieClip();
mc.graphics.beginFill(0xFF1230);
mc.graphics.drawRect(mouseX, mouseY, 100, 80);
mc.graphics.endFill();

However, When I begin to try to adjust where the rectangle gets drawn, like this:

mc.graphics.drawRect(mouseX - 50, mouseY - 50, 100, 80);

the rectangle gets drawn but will constantly flicker.

I have tried many variations of the line that gives an error, trying different data types and separating out the math into its own variable, but the same thing happens.

Has anyone experienced anything like this before? Any help or information is much appreciated!

2

There are 2 answers

0
Iggy On

Instead of redrawing the rectangle each frame you could simply scale it.

var mc:MovieClip = new MovieClip();
mc.graphics.beginFill(0xFF1230);
mc.graphics.drawRect(0,0,1,1);
mc.graphics.endFill();
addChild(mc);

stage.addEventListener(Event.ENTER_FRAME, loop);
function loop(e:Event) {
    mc.scaleX = mouseX;
    mc.scaleY = mouseY; 
}
1
Daniel On
  1. it's more likely an issue with the event listener set up than the drawing code. I'm guessing you're using MouseEvent. You will need to post that code for anyone to help you with that (likely the mouse target is changing as soon as you draw the rectangle beneath)

  2. you should not need to redraw the graphics, you're going to find that this will effect the frame rate over time, unless you clear() it every time. You are better off to offset the rectangle, and move the position of the movie clip.

like this:

var mc:MovieClip = new MovieClip();
mc.graphics.beginFill(0xFF1230);
mc.graphics.drawRect(-50, -50, 100, 80);
mc.graphics.endFill();
addChild(mc);

stage.addEventListener(MouseEvent.MOUSE_MOVE, onMove);
function onMove(e:MouseEvent):void {
    mc.x = mouseX;
    mc.y = mouseY; 
}