Jump to content

Torque 2D Tips/Tricks & Resources


Recommended Posts

Integrating Google AdMob Android: Requires source changes:


In this resource i will be using interstitial ads as an example: mainly because these are the ads i have used and because i simply am not sure how to load banner ads yet lol


This is only tested with the latest development branch on github as it has some updates to the android end of things.


First thing to do is add the google admob sdk to your project so in your build.gradle file for the app add this under the dependencies

 

dependencies {
    implementation 'com.google.android.gms:play-services-ads:18.2.0'
}

 

Then in the AndroidManifest.xml u need to add meta data to your application settings like so

 

 
 
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
        android:hardwareAccelerated="true" android:hasCode="true"
        tools:ignore="GoogleAppIndexingWarning">
        
            android:name="com.google.android.gms.ads.APPLICATION_ID"
            android:value="ca-app-pub-################~##########"/>
        
android:value="your app id on admob"

Then in T2DUtilities.java add these 2 functions before the last curly brace
  [code2=BBCODE40_JAVA]public static void ToggleLoadAd(final Context context, final boolean show) { if (show) { final Activity activity = (Activity) context; activity.runOnUiThread(new Runnable() { @Override public void run() { MobileAds.initialize(activity, new OnInitializationCompleteListener(){ @Override public void onInitializationComplete(InitializationStatus initializationStatus) { } }); mInterstitialAd = new InterstitialAd(activity); mInterstitialAd.setAdUnitId("ca-app-pub-################/###########"); mInterstitialAd.loadAd(new AdRequest.Builder().build()); Log.i("TAG", "The interestitial is being loaded"); mInterstitialAd.setAdListener(new AdListener() { @Override public void onAdClosed() { //load new ad mInterstitialAd.loadAd(new AdRequest.Builder().build()); } });   } }); }Log.i("TAG","The ad load is set to false"); }   public static void ToggleShowAd(final Context context, final boolean show) { if (show) { final Activity activity = (Activity) context; activity.runOnUiThread(new Runnable(){ @Override public void run() { if (mInterstitialAd.isLoaded()) { mInterstitialAd.show(); Log.i("TAG", "Showing the ad"); } else { Log.i("TAG", "The interestitial is not ready"); } }   });Log.i("TAG", "The ad show is set to false"); } }

mInterstitialAd.setAdUnitId("ca-app-pub-################/###########"); should be your interstitial ad unit id.


These two functions should make sense if you have been going through the admob tutorials on googles site basically one function loads the ad and when it sees that that particular ad has been closed it will load another and the other function displays the loaded ad.


Now to link it up with scripts in torque:


In source\platformAndroid\T2DActivity.h after

extern bool android_DumpDirectories(const char *basePath, const char *path, Vector &directoryVector, S32 depth, bool noBasePath);

 

add

 

extern void toggleLoadAd(bool show);
extern void toggleShowAd(bool show);

 

then in T2DActivity.cpp after the double timeGetTime function closes add these 2 functions

 

void toggleLoadAd(bool show)
{
	// Attaches the current thread to the JVM.
	jint lResult;
	jint lFlags = 0;
 
	JavaVM* lJavaVM = platState.engine->app->activity->vm;
	JNIEnv* lJNIEnv = platState.engine->app->activity->env;
 
	JavaVMAttachArgs lJavaVMAttachArgs;
	lJavaVMAttachArgs.version = JNI_VERSION_1_6;
	lJavaVMAttachArgs.name = "NativeThread";
	lJavaVMAttachArgs.group = NULL;
 
	lResult=lJavaVM->AttachCurrentThread(&lJNIEnv, &lJavaVMAttachArgs);
	if (lResult == JNI_ERR) {
		return;
	}
 
	// Retrieves NativeActivity.
	jobject lNativeActivity = platState.engine->app->activity->clazz;
	jclass ClassNativeActivity = lJNIEnv->GetObjectClass(lNativeActivity);
 
	jmethodID getClassLoader = lJNIEnv->GetMethodID(ClassNativeActivity,"getClassLoader", "()Ljava/lang/ClassLoader;");
	jobject cls = lJNIEnv->CallObjectMethod(lNativeActivity, getClassLoader);
	jclass classLoader = lJNIEnv->FindClass("java/lang/ClassLoader");
	jmethodID findClass = lJNIEnv->GetMethodID(classLoader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
	jstring strClassName = lJNIEnv->NewStringUTF("com.garagegames.torque2d.T2DUtilities");
	jclass T2DUtilitiesClass = (jclass)lJNIEnv->CallObjectMethod(cls, findClass, strClassName);
	jmethodID MethodT2DUtilitiesClass = lJNIEnv->GetStaticMethodID(T2DUtilitiesClass, "ToggleLoadAd", "(Landroid/content/Context;Z)V");
	lJNIEnv->CallStaticVoidMethod(T2DUtilitiesClass, MethodT2DUtilitiesClass, lNativeActivity, (jboolean)show);
 
	// Finished with the JVM.
	lJavaVM->DetachCurrentThread();
}
 
void toggleShowAd(bool show)
{
	// Attaches the current thread to the JVM.
	jint lResult;
	jint lFlags = 0;
 
	JavaVM* lJavaVM = platState.engine->app->activity->vm;
	JNIEnv* lJNIEnv = platState.engine->app->activity->env;
 
	JavaVMAttachArgs lJavaVMAttachArgs;
	lJavaVMAttachArgs.version = JNI_VERSION_1_6;
	lJavaVMAttachArgs.name = "NativeThread";
	lJavaVMAttachArgs.group = NULL;
 
	lResult=lJavaVM->AttachCurrentThread(&lJNIEnv, &lJavaVMAttachArgs);
	if (lResult == JNI_ERR) {
		return;
	}
 
	// Retrieves NativeActivity.
	jobject lNativeActivity = platState.engine->app->activity->clazz;
	jclass ClassNativeActivity = lJNIEnv->GetObjectClass(lNativeActivity);
 
	jmethodID getClassLoader = lJNIEnv->GetMethodID(ClassNativeActivity,"getClassLoader", "()Ljava/lang/ClassLoader;");
	jobject cls = lJNIEnv->CallObjectMethod(lNativeActivity, getClassLoader);
	jclass classLoader = lJNIEnv->FindClass("java/lang/ClassLoader");
	jmethodID findClass = lJNIEnv->GetMethodID(classLoader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
	jstring strClassName = lJNIEnv->NewStringUTF("com.garagegames.torque2d.T2DUtilities");
	jclass T2DUtilitiesClass = (jclass)lJNIEnv->CallObjectMethod(cls, findClass, strClassName);
	jmethodID MethodT2DUtilitiesClass = lJNIEnv->GetStaticMethodID(T2DUtilitiesClass, "ToggleShowAd", "(Landroid/content/Context;Z)V");
	lJNIEnv->CallStaticVoidMethod(T2DUtilitiesClass, MethodT2DUtilitiesClass,lNativeActivity, (jboolean)show);
 
	// Finished with the JVM.
	lJavaVM->DetachCurrentThread();
}

 

in the same file in the static int engine_init_display there is if (SetupComplete == false)

inside this if statement add

 

    if (SetupCompleted == false)
    {
		toggleLoadAd(false);
		toggleShowAd(false);

 

Further down in the same file you will see consolefunctions after the console function for dumpFontList around line 2068 add

 

ConsoleFunction(loadAd,void,1,1,"load ad")
{
	toggleLoadAd(true);
}
 
ConsoleFunction(showAd,void,1,1,"show ad")
{
	toggleShowAd(true);
}

 

Now in your games module you call loadAd() to load an ad and showAd to show an ad whenever and wherever you like in your script. What i think is good practice is to loadAd when your game is launched this way whenever you decide to show the ad it should be loaded properly and ready for displaying to the user. Included in this code is a bit of code that will be executed if you try to show an ad that isnt ready so it shouldnt cause any problems for end users.

Link to post
Share on other sites

Android: Testing if device is Tablet or Phone


This one is a bit hit or miss. Android has no definite way of telling if a device is a tablet unlike ios (i will upload later how to work for ipads)


So we will be determining it by the set standard set by googles site but exposing it to script so u can set different functions for different devices(or at least larger screen sizes)


So in android studio you will see the res folder (not the generated one) inside it you should see a folder called values, expand it and you will see strings.xml


open it and add

 

false

 

between the


Next right click on the res folder and choose new > Android resource directory


name this folder values-sw600dp


Inside this create a new Values resource file and call it attr


the whole file should be:

<?xml version="1.0" encoding="utf-8"?>

    true

 

repeat this process for a folder called values-xlarge


Now for the meat of the code


In T2DUtilities.java at the bottom before the final curly brace add:

 

	public static int GetDeviceType()
	{
		if (isTabletSize)
			{
				return 1;
			}
			else
			{
				return 0;
			}
	}
 
}

 

in MyNativeActivity.java


just after

 

public class MyNativeActivity extends NativeActivity {
    static {
        System.loadLibrary("openal");
    }

 

add:

 

public static boolean IsTabletSize;
    }

 

scroll on down to about line 40 you should see

 

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

 

after this add:

 

        boolean tabletSize = getResources().getBoolean(R.bool.isTablet);
        if(tabletSize){
            IsTabletSize = true;
        }
 
    }
 
    public static boolean getData()
    {
        return IsTabletSize;
    }

 

now to link it all to script!


In T2DActivity.h after the externs add

 

extern int GetDeviceType();

 

then in T2DActivity.cpp


after the int android_checkAlert() function


create this function:

 

int GetDeviceType(){
	// Attaches the current thread to the JVM.
	jint lResult;
	jint lFlags = 0;
 
	JavaVM* lJavaVM = platState.engine->app->activity->vm;
	JNIEnv* lJNIEnv = platState.engine->app->activity->env;
 
	JavaVMAttachArgs lJavaVMAttachArgs;
	lJavaVMAttachArgs.version = JNI_VERSION_1_6;
	lJavaVMAttachArgs.name = "NativeThread";
	lJavaVMAttachArgs.group = NULL;
 
	lResult=lJavaVM->AttachCurrentThread(&lJNIEnv, &lJavaVMAttachArgs);
	if (lResult == JNI_ERR) {
		return 0;
	}
 
	// Retrieves NativeActivity.
	jobject lNativeActivity = platState.engine->app->activity->clazz;
	jclass ClassNativeActivity = lJNIEnv->GetObjectClass(lNativeActivity);
 
	jmethodID getClassLoader = lJNIEnv->GetMethodID(ClassNativeActivity,"getClassLoader", "()Ljava/lang/ClassLoader;");
	jobject cls = lJNIEnv->CallObjectMethod(lNativeActivity, getClassLoader);
	jclass classLoader = lJNIEnv->FindClass("java/lang/ClassLoader");
	jmethodID findClass = lJNIEnv->GetMethodID(classLoader, "loadClass", "(Ljava/lang/String;)Ljava/lang/Class;");
	jstring strClassName = lJNIEnv->NewStringUTF("com.garagegames.torque2d.T2DUtilities");
	jclass T2DUtilitiesClass = (jclass)lJNIEnv->CallObjectMethod(cls, findClass, strClassName);
	jmethodID MethodT2DUtilities = lJNIEnv->GetStaticMethodID(T2DUtilitiesClass, "GetDeviceType", "()I");
	jint jret = lJNIEnv->CallStaticIntMethod(T2DUtilitiesClass, MethodT2DUtilities);
 
	if(jret == 1)
	{
		__android_log_write(ANDROID_LOG_INFO,"TAG","setting device type is tablet");
		Con::setVariable("$deviceType","tablet");
	} else
	{
		__android_log_write(ANDROID_LOG_INFO,"TAG","setting device type is phone");
		Con::setVariable("$deviceType","phone");
	}
 
	lJNIEnv->DeleteLocalRef(strClassName);
	// Finished with the JVM.
	lJavaVM->DetachCurrentThread();
	return jret;
}

 

Then find

 

if (SetupCompleted == false)

 

and inside this if statement add

 

GetDeviceType();

 

This will make sure the code is run when the app is started and it will assign the values. Now anywhere inside the scripts for your game you would do this:

 

if ($deviceType $= "tablet")
{
//make tablet player suffer
}
else
{
//haha u got a phone
}

 

I mostly use this just for setting different camera zooms and difficulty settings for different devices so you can design your game to work on tablet and then zoom in a bit and now you have it set for phone. Also a different hud for each device is a must usually.

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...