Question

I'm trying to make a program that pulses to the beat of a song, with a wave pattern on top, but the wave pattern seems to be behind everything. I know how to change the index of a child added to the stage, but I have no clue on how to set the index value of a graphic. Here's my code(if relevant):

import flash.display.Sprite;
import flash.display.Graphics;
import flash.events.Event;
import flash.media.Sound;
import flash.media.SoundChannel;
import flash.media.SoundMixer;
import flash.net.URLRequest;
import flash.utils.ByteArray;
import flash.text.TextField;

var snd:Sound = new Sound();
var req:URLRequest = new URLRequest("SuperHexagonMusic.mp3");
var channel:SoundChannel;

stage.addEventListener(Event.ENTER_FRAME, everyFrame);

snd.load(req);
channel = snd.play();
channel.addEventListener(Event.SOUND_COMPLETE, onPlaybackComplete);

function everyFrame(event:Event):void
{
    pulse.alpha = channel.leftPeak * 3;
    var bytes:ByteArray = new ByteArray();
    const PLOT_HEIGHT:int = 200;
    const CHANNEL_LENGTH:int = 256;

    SoundMixer.computeSpectrum(bytes, false, 0);

    var g:Graphics = this.graphics;

    g.clear();

    g.lineStyle(0, 0x000000);
    g.beginFill(0x000000);
    g.moveTo(0, PLOT_HEIGHT);

    var n:Number = 0;

    for (var i:int = 0; i < CHANNEL_LENGTH; i++)
    {
        n = (bytes.readFloat() * PLOT_HEIGHT);
        g.lineTo(i * 2.5, PLOT_HEIGHT - n);
    }

    g.lineTo(CHANNEL_LENGTH * 2.5, PLOT_HEIGHT);
    g.endFill();

    g.lineStyle(0, 0xFFFFFF);
    g.beginFill(0xFFFFFF, 0.5);
    g.moveTo(CHANNEL_LENGTH * 2.5, PLOT_HEIGHT);

    for (i = CHANNEL_LENGTH; i > 0; i--)
    {
        n = (bytes.readFloat() * PLOT_HEIGHT);
        g.lineTo(i * 2.5, PLOT_HEIGHT - n);
    }  

    g.lineTo(0, PLOT_HEIGHT);
    g.endFill();
}

function onPlaybackComplete(event:Event):void
{
    stage.removeEventListener(Event.ENTER_FRAME, everyFrame);
}

What I'm hoping for is the constructed wave pattern to be on top of the pulse, but the current code produces this result:

In the image, you can see the end of the wave pattern poking out behind the pulse.

So in short: How might I bring that wave pattern to the front?

Was it helpful?

Solution

The parent's Graphics is always behind all parent's children. You should make yourself another Sprite or Shape object, place it on top of your display list, and draw on its graphics instead.

var spectrum:Shape=new Shape();
addChild(spectrum); // if last added, will be on top
function everyFrame(e:Event):void {
     var g:Graphics=spectrum.graphics; // that's all you need to change!
     // the rest of code follows
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top