RizukiHiroto
RizukiHiroto

Reputation: 37

How to change a sprite color when a button has been clicked AS3

i have a sprite (circle), i made it with actionscript. Here is the pseudocode:

    var board:Sprite = new Sprite();
    var spDot:Sprite = new Sprite()
    spDot.graphics.lineStyle(1,0x0000CC);   
    spDot.graphics.beginFill(0xFFFFFF); //white;
    spDot.graphics.drawCircle(0,0,dZ);  
    spDot.graphics.endFill();
    spDot.name="v";
    board.addChild(spDot);

and i have a button "btnA" to change a current sprite color (white) to black.

btnA.addEventListener(MouseEvent.CLICK, changeColor);
function changeColor(evt:MouseEvent){
     (board.getChildByName("v") as Sprite).graphics.beginFill(0x000000);
}

but, my problem, it returned error in this part: (board.getChildByName("v") as Sprite).graphics.beginFill(0x000000);

Actually i just guessed to use (board.getChildByName("v") as Sprite).graphics.beginFill(0x000000); to change the color. Do you have any idea? Thank you!

Upvotes: 2

Views: 3714

Answers (2)

Nicolas Siver
Nicolas Siver

Reputation: 2885

I would recommend to don't disclosure implementation of display object that should be colorised, if you are agree with this statement, you could use ColorTransform ;)

The ColorTransform class lets you adjust the color values in a display object. The color adjustment or color transformation can be applied to all four channels: red, green, blue, and alpha transparency.

Example:

btnA.addEventListener(MouseEvent.CLICK, buttonDidClick);

function buttonDidClick(e:MouseEvent) {
    transformColor(board.getChildByName("v"), 0x000000);
}

function transformColor(target:DisplayObject, color:uint):void {
    var colorTransform:ColorTransform = new ColorTransform();
    colorTransform.color = color;
    target.transform.colorTransform = colorTransform;
}

Upvotes: 2

Florian Salihovic
Florian Salihovic

Reputation: 3961

This easiest way would be clearing the graphics data and redraw into the graphics object.

function drawCircle(sprite:Sprite, radius:Number = 40, fillColor:int = 0):Sprite
{
  if (!sprite) return null;

  const g:Graphics = sprite.graphics;

  g.clear();
  g.lineStyle(1, 0x0000CC);   
  g.beginFill(fillColor);
  g.drawCircle(0, 0, radius);
  g.endFill();

  return sprite;
}

Also, i highly recommend not to use implicit calls when you need expect a certain type:

function changeColor(evt:MouseEvent)
{
  // hides the fact, that you're having an instance of am unexpected type
  (board.getChildByName("v") as Sprite).graphics.beginFill(0x000000);
}

Will lead to a 1009/null pointer although you have a valid reference.

function changeColor(evt:MouseEvent)
{
  // fails fast - for example when you change from sprite to bitmap.
  Sprite(board.getChildByName("v")).graphics.beginFill(0x000000);
}

Failing fast is in this case the suitable way to cast.

Upvotes: 1

Related Questions