
//Called when application is started.
function OnStart()
{
	//Lock screen orientation to Landscape.
	app.SetOrientation( "Landscape" );

    //Set full screen mode
    app.SetScreenMode( "Full");
    
	//Create the main background layout.
	lay = app.CreateLayout( "Linear", "Horizontal,VCenter,FillXY" );
	lay.SetBackground( "/Sys/Img/Tile.png", "repeat" );
	   
	imgPad = app.CreateImage( "/Sys/Img/JoyPad.png", -2,0.5, "" );
	imgPad.SetOnTouch( imgPad_OnTouch );     
	imgPad.SetMargins( 0.6,0.2,0.01, 0.01 );
	lay.AddChild( imgPad );  

	//Add main layout to app.
	app.AddLayout( lay );
}


//Called when joypad image is touched.
function imgPad_OnTouch( e )
{          	

	if( e.action=="Move" || e.action=="Down" ) {
	   CircleDrive( imgPad, e.x[0], e.y[0] );       
	}
}


//Drive C and D motors using x/y posn within a circle.
function CircleDrive( obj, x, y )
{
	//Adjust x and y values so they range from -1.0 to +1.0    
	x = 2 * (x-0.5);  y = -2 * (y-0.5);    

	//Calc velocity using distance from center.
	var vel = Math.sqrt( x*x + y*y );

	//Get direction (fwd or rev).
	var dir = (y > 0 ? 1 : -1 );

	//Set turn ratio.
	var turnB = 1, turnC = 1;
	if( x < 0 ) turnB = 1+x;
	else if( x > 0 ) turnC = 1-x;

	//Special case for fast turn.
	if( y > -0.1 && y < 0.1 ) {
		turnB = x;  turnC = -x;  dir = 1;
	}
app.ShowPopup( dir * vel * turnB * turnC * 100, 0 );
}