Search code examples
actionscript-3flash-builder

How to draw a star in AS3


i this my code this way but is not coming out the right way. I don't know what i missing, i can't figure out. if some want want to help!!

private var _color:uint;
private var _radius:int;

public function Star(c:uint = 0xff0000, r:int = 15)
{
  _color = c;
  _radius = r;

  createStar();

}       
    private function createStar():void      
    {           
      this.graphics.lineStyle(3,_color);
      this.graphics.moveTo(_radius,0);

      for(var i:int = 1; i < 11; i++)
      {
        var radius2:Number = _radius;

        if (i % 2 > 0)
      }
      _radius = _radius/2;
      var angle:Number = (6.28 / 5) * i;
      this.graphics.lineTo(Math.cos(angle) * radius2, Math.sin(angle) * radius2);
   }
}

Solution

  • your createStar() function looks pretty bad:

    • unfinished conditional (if (i % 2 > 0)) which is a syntax error
    • hardcoded value: var angle:Number = (6.28 / 5) * i;, maybe not that bad assuming 6.28 is supposed to be Math.PI * 2, but the i counter doesn't belong there
    • drawing a single line (this.graphics.lineTo(Math.cos(angle) * radius2, Math.sin(angle) * radius2);) and expecting a star

    you might want to try something like this:

    private function createStar():void      
    {           
        graphics.lineStyle(3,_color);
        graphics.moveTo(_radius,0);
    
        var angleIncrement = Math.PI / 5;//5 pointed star -> 10 point arround the circle (360 degrees or Math.PI * 2): 5 outer points, 5 inner points
        var ninety:Number = Math.PI * .5;//offset the rotation by 90 degrees so the star points up
    
        for(var i:int = 0; i <= 10; i++){//for each point
            var radius:Number = (i % 2 > 0 ? _radius : _radius * .5);//determine if the point is inner (half radius) or outer(full radius)
            var px:Number = Math.cos(ninety + angleIncrement * i) * radius;//compute x
            var py:Number = Math.sin(ninety + angleIncrement * i) * radius;//and y using polar to cartesian coordinate conversion
            if(i == 0) graphics.moveTo(px,py);//move the 'pen' so we don't draw lines from (0,0)
            graphics.lineTo(px,py);//draw each point of the star
        }
    }