Search code examples
actionscript-3flashyoutubeplayer-stage

Can't centre the YouTube player to the stage in Flash CS5 (AS3)


I have a YouTube video playing in Flash but I want to centre it to the stage. At the moment it either goes to the top left corner or the bottom right corner.

Here's the code I have that loads the player and the video. The video plays no problem, I just want to centralise it on the stage.

stop();

Security.allowDomain("www.youtube.com");

var my_player:Object;

var my_loader:Loader = new Loader();
my_loader.load(new URLRequest("http://www.youtube.com/apiplayer?version=3"));
my_loader.contentLoaderInfo.addEventListener(Event.INIT, onLoaderInit);

function onLoaderInit(e:Event):void{
addChild(my_loader);
my_player = my_loader.content;
my_player.addEventListener("onReady", onPlayerReady);
} 

function onPlayerReady(e:Event):void{
my_player.setSize(600,300);
my_player.cueVideoById("76BboyrEl48",0);
my_player.x = stage.stageWidth / 2;
my_player.y = stage.stageHeight / 2;
} 

play_btn.addEventListener(MouseEvent.CLICK, playVid);
function playVid(e:MouseEvent):void {
my_player.playVideo();
}
pause_btn.addEventListener(MouseEvent.CLICK, pauseVid);
function pauseVid(e:MouseEvent):void {
my_player.pauseVideo();
}

As you can see I've tried using the .x = stageWidth / 2; method but that just moves the player to the bottom right and without it, it stays in the top left corner.


Solution

  • Try this:

    my_player.x = stage.stageWidth/2 - my_player.width/2;
    my_player.y = stage.stageHeight/2 - my_player.height/2;