Jump to content

BabylonJS and Android using Basic4Android


eps
 Share

Recommended Posts

A couple of posters have mentioned getting BabylonJS projects on to Android.

This is my take on this, the whole code developed using Basic4Android (sometimes called B4A).  It is a fairly mature platform - I've been using it for about 7 years now.

For Basic4Android you can develop an App which creates a WebView which then loads the HTML which then loads the Javascript, which access BabylonJS.

You can, obviously, send variables to the HTML (pretty standard) and/or pass variables back to the Android App - I'll leave the code in there to enable you to do that as well as I think it's quite useful to do and to see how it's been done.

You WILL need some libraries, which are only available to Licensed Users (but at no extra cost). They are :

WebViewExtras2 (ver 2.20)

WebViewSettings (ver 1.31)

JavaObject (2.05)

Reflection (2.40)

Phone (2.50)

IME (1.10)

I use other libraries in addition to these - but they are to do with Firebase / Admob and a few graphical elements.  StringUtils and RuntimePermissions.

B4A demo code in full.  This should work, but I'm happy to help out or you can always post questions on the B4A Forum ( https://www.b4x.com/android/forum/ ).  I'm using the latest release version of B4A which is 8.50 but you shouldn't necessarily need that version - probably only around 6.80 or later.

	#Region  Project Attributes
	#FullScreen: True
	#IncludeTitle: False
	#ApplicationLabel: Demo
	#VersionCode: 1
	#VersionName: 
	'SupportedOrientations possible values: unspecified, landscape or portrait.
	#SupportedOrientations: landscape
	#CanInstallToExternalStorage: False
	#End Region
	 
	#Region  Activity Attributes
	#FullScreen: True
	#IncludeTitle: False
	#End Region
	 
	Sub Process_Globals
	'These global variables will be declared once when the application starts.
	'These variables can be accessed from all modules.
	 
	End Sub
	 
	Sub Globals
	'These global variables will be redeclared each time the activity is created.
	'These variables can only be accessed from this module.
	Dim wv As WebView
	Dim wve As WebViewExtras
	Dim wvs As WebViewSettings
	   Private ime1 As IME
	 
	   Private ActivityParent As JavaObject 
	End Sub
	 
	Sub Activity_Create(FirstTime As Boolean)
	'Do not forget to load the layout file created with the visual designer. For example:
	'Activity.LoadLayout("Layout1")
	wv.Initialize("wv")
	wve.addWebChromeClient(wv,"wve")
	wvs.setAllowFileAccess(wv,True)
	wvs.setAppCacheEnabled(wv,True)
	wvs.setDOMStorageEnabled(wv,True)
	 
	Activity.AddView(wv,0,0,100%x,100%y)
	wv.LoadUrl("file:///android_asset/index.html?parameter1="&variableValue&"")
	   ime1.Initialize("ime1")
	   ime1.AddHeightChangedEvent
	   Dim jo As JavaObject = Activity
	   jo.RunMethodJO("getContext", Null).RunMethodJO("getWindow", Null).RunMethod("setSoftInputMode", _
	     Array As Object(0x20))
	   ActivityParent = jo.RunMethodJO("getParent", Null) 
	End Sub
	 
	Sub Activity_Resume
	 
	End Sub
	 
	Sub Activity_Pause (UserClosed As Boolean)
	 
	End Sub
	 
	Sub IME1_HeightChanged (NewHeight As Int, OldHeight As Int)
	   CallSubDelayed(Me, "AfterChange")
	End Sub
	 
	Sub AfterChange
	   Dim ajo As Panel = Activity
	   Dim width As Int = ActivityParent.RunMethod("getMeasuredWidth", Null)
	   Dim height As Int = ActivityParent.RunMethod("getMeasuredHeight", Null)
	   If width = 0 Or height = 0 Then Return
	   ajo.width = width 'update the "activity" width and height
	   ajo.height = height
	   wv.width = width
	   wv.height = height
	   wv.ZoomEnabled = False
	End Sub
	 
	Sub start_rewardvideoandroidfunction (variable As String)
	'Log("Got back to Android "+variable)
	Log("*** Got back to Android !! "& variable)
	End Sub
	

Of course you will need to make sure that the HTML and Javascript reside in the correct (sub)directories.

Just passing a single variable to the Javascript, but could pass more.

HTML

	<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html" charset="utf-8"/>
    <title>HTML5 Demo</title>
    <!--- link to the last version of babylon --->
    <!-- <script src="scripts/hand.minified-1.2.js" type="text/javascript"></script> -->
    <script src="js/pep.js" type="text/javascript"></script>
    <script src="js/babylon.3.1.mini.js" type="text/javascript"></script>
    <script src="js/babylon.gui.js" type="text/javascript"></script>
    <style type="text/css">
        html, body {
            overflow: hidden;
            width   : 100%;
            height  : 100%;
            margin  : 0;
            padding : 0;
        }
	        #renderCanvas {
            width   : 100%;
            height  : 100%;
        }
        #scoreLabel {
            position:absolute;
            top:20px;
            left : 20px;
            color:white;
            font-size: 1em;
        }
        #livesLabel {
            position:absolute;
            bottom:20px;
            left : 20px;
            color:white;
            font-size: 1em;
        }
        #highScoreLabel {
            position:absolute;
            bottom:20px;
            right : 20px;
            color:white;
            font-size: 1em;
        }
        #waveLabel {
            position:absolute;
            top:20px;
            right : 20px;
            color:white;
            font-size: 1em;
        }
    </style>
</head>
<body>
    <canvas id="renderCanvas" touch-action="none"></canvas>
    <div id="scoreLabel">SCORE : 0</div>
    <div id="livesLabel">LIVES : </div>
    <div id="highScoreLabel">HIGH SCORE : </div>
    <div id="waveLabel">WAVE :   1</div>
    <script src="js/app.js" type="text/javascript"></script>
    <script>
        window.addEventListener('DOMContentLoaded', function () {
        
    var parameters = location.search.substring(1).split("&");
	    var temp = parameters[0].split("=");
    l = unescape(temp[1]);
    
            BjsApp.init(l);
        });
</script>
</body>
</html>
	

Javascript

	/// <reference path="babylon.d.ts" />
/// <reference path="babylon.js" />
/// <reference path="babylon.gui.js" />
	var BjsApp = BjsApp || {};
	var livesP1 = 3;
	BjsApp.init = function (livesFromApp) {
	    livesP1 = livesFromApp;  //set here, but defined globally - not any more, passed in from Android App to allow player to get rewarded for watching an advert, gain extra life
 
	    document.getElementById("livesLabel").innerHTML = "LIVES : " + livesP1;  //Update the HTML div accordingly - I obviously do this quite a bit at the moment but this is mainly to save on having to code the graphical parts of those and prettify them.
 
	//Do your own Javascript stuff here!!!!
	                    console.log('The Aliens have landed about to go back to Android....'+ score);
                    //Android.startRewardVideoAndroidFunction(score);
                    Android.CallSub('start_rewardvideoandroidfunction',true,score);
	}
	 
	

 

I've, obviously, removed a whole load of code - but hopefully there should be enough here for anyone to follow.  As I said I'm happy to help out or post questions on the B4A forum.

Link to comment
Share on other sites

16 hours ago, Deltakosh said:

Thank you so much for sharing!!

No worries, hopefully it will help others get started..

 

It took me a few years to find Basic4Android when looking for a decent toolset to create Android Apps which offered enough flexibility to delve deeper if needed but not too much coding for codings sake.  I had an idea for a 3D game a few years (4 or 5!!) ago and then went looking for a 3D framework.  I came across BabylonJS and have just about achieved my goal for this now, thanks to you and David R + others along the way. :)  My game is very much a 0.1 version of where I want to get it to, but as always there are other time pressures.  0.1 is just about viable - hopefully if there is interest I am hoping to improve on it rapidly.

Link to comment
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.
Note: Your post will require moderator approval before it will be visible.

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.

Loading...
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...