Is it possible to control the scene in the Unity3D Plugin by using JavaScript? The JavaScript-Code should run in the context of the browser and not in the context of the Unity3D Plugin?
I have to transform, delete and add objects in the scene.
Perhaps do you have an example.
Thanks for any advice.
Yes, it's possible - at least, I know I've done it, but it was quite some time ago.
Here's the demo page I put together back then.
Feel free to look in the page's source code. Most of it comes from Unity's docs and examples. I just made a simple wrapper for the sending and receiving of messages to/from the Unity web player, and adapted the code a little.
My code is based on Prototype.js, so you'll have to do some minor rewrites if you're using jQuery (like most people these days), but it shouldn't be too bad. Or you can just use Unity's pre-made stuff.
I'm not usually a Unity coder so I can't tell you exactly how to set up the Unity-side of things (I did make the simple shader-based demo you see, but I've lost the source files, I think), but as I recall, it was simply a matter of creating a game object with a set of public methods. Those methods can then be called via JavaScript. Simple as that.
Basically, from the JS-side, all you have to do is this:
var player = document.getElementById("UnityObject");
player.sendMessage("name of game object", "name of method", "argument");
You can also send messages from the a GameObject back to JavaScript, if you want. It doesn't happen in the demo, but it should work. Check the source for details.
Related
I have two games I made in Phaser js. What my plan is, is to make a third js file thats only function is to proc the files. What I mean is to initiate the controller file which will initiate the first game. After that game is over by a certain condition, it will proc a global variable across files saying its done. This will cause the master file to kill the first game and fire off the second. Can someone direct me in how to do this? I know these questions don't usually get answered without code so I'll include a pastebin link(since it's a lot of code) to the two games so you can verify that I've actually done the work.
Game 1: http://pastebin.com/cPTn26rz
Game 2: http://pastebin.com/2mCHvTLm
Looking at your code I'm thinking you might be relatively new to Phaser, and you might not yet have heard about Phaser's State Manager.
In Phaser you can use states to create a standard game structure like this:
Loading Screen
Main Menu
Game
Game Over
In your particular case, you could just have something like this:
Game 1
Game 2
To start with I might recommend Bryan Bibat's HTML 5 Shoot 'em Up in an Afternoon (free to read online, but worth money). It was my first introduction to the state functionality.
Alternatively, Emanuele Feronato's Understanding Phaser states is pretty basic (and has a rough ending), but should provide a quick understanding of Phaser's states.
It might be a little advanced initially, but I actually got quite a bit out of Interphase 1's state manager section, once you're ready to get a bit more advanced, but you should be able to get what you need from either of the tutorials above.
I am trying to figure out any and all ways to prevent CSS modification and DOM modification of specific elements. I understand this might not be completely possible or that a talented developer could get around it, however, I am not so concerned about people potentially getting around it, I just want to stop newbies. In particular those using jQuery. An example would be to delete certain properties on prototype objects etc..
But why you need/want this? If you want to "protect" your code, you can use some JavaScript minifier as Google Closure Compiler or YUI compressor. They will rewrite your script and it will be difficult to read by a human. Nowadays, with tools like Firebug and Grease Monkey it's almost impossible to do what you want.
Don't use CSS or JavaScript :p Depend completely on server side checks etc.
You cannot stop anyone from messing with your javascript or your objects in the page. The way the browser is designed, your code and objects in your page are simply not protected. Everything from bookmarklets to javascript entered at a console to browser plug-ins can mess with your page and code and variables. That is the architecture of a browser.
What you can do is make things a little more difficult such that a little more work is required for some things. Here are a couple of things you could do:
Obfuscating/compressing/minimizing your code will do things like remove comments, remove whitespace, remove some linebreaks, shorten variable names, etc... That does not prevent anyone from modifying things, but does make it more work to understand and figure out.
Putting variables inside closures and not using globals. This makes it harder to directly modify variables from outside of your scripts.
Keep all important data and secrets on your server. Use ajax calls to ask the server to carry out operations using that data or secrets such that the important information is never available in the browser client.
You cannot keep anyone from modifying the DOM. There simply are no protections against that. Your code can check the DOM and refuse to operate if the DOM has been messed with in non-standard ways. But, of course, the code would then be modified to remove that check too.
If you are looking for a jquery specific solution a crude approach will involve altering the jQuery ($) function and replacing it with a custom one that delegates to the original function only if the provided selector does not match the element you want to secure.
(function(){
jQueryOrig = jQuery;
window.jQuery = window.$ = function(){
if (jQueryOrig("#secure").is(arguments[0])) {
throw new Error("Security breach");
} else return jQueryOrig.apply(this, arguments);
}
}());
Of course people using direct DOM manipulation would not be affected.
Also, if you are actually including arbitrary third party code in your production code, you should take a look at Caja ( http://code.google.com/p/google-caja/ ), which limits users to a subset of javascript capabilities. There is a good explanation regarding Caja here : http://due-diligence.typepad.com/blog/2008/04/web-20-investor.html .
This is possible but requires that the JS file to always be loaded from your server. Using observers you can lock CSS properties and using the on DOM remove/add listeners you can lock it to a parent. This will be enough to discourage most modification.
You can actually go a step further and modify core javascript functions making it nearly impossible to modify the DOM without loading the JS file locally or through a proxy. Further security can be added by doing additional domain checks to make sure the JS file is loaded from where it is supposed to be loaded from.
You can make everything in Flash. In Chrome, there's even a bug that prevents users from opening a console if the flash element has focus (not sure how exactly this works, but you can see an example at http://www.twist-cube.com or http://www.gotmilk.com). Even if users do manage to get a console open (which isn't that hard...), still about all you can do is change the shape of the element.
So I'm sure this is probably at least mostly insane, but I was just thinking about AS3/JS interaction and it got me wondering - does anyone know exactly how inefficient calling JS via AS3 is? For example, if you do the following:
import flash.external.ExternalInterface;
ExternalInterface.call("(function() { /* here's a block of code */ })");
Do these calls need to be eval()ed in the end, or are they able to be passed natively?
Regardless: let's be hypothetical for a second and say that you were a heretic and actually stored a good deal of Javascript within a utility SWF (1x1, offscreen, whatever), and had basic DOM events bound to hand those events to AS3 when they fire, which thus uses ExternalInterface to execute the JS immediately - thus the only part of your Javascript that is ever loaded is a little bit to communicate with Flash. A naive person might even say "you could condense numerous JS files into one loaded SWF file, separating them into different MC's or whatever!", but really, that's not the point, and that won't help us any after the page is already loaded.
I've used AS3 and its Socket class in lieu of XHR polling (etc), so I haven't been disappointed with AS3/JS interaction so far. AFAIK AS3 is executed inside the Flash VM which means that it is automatically less efficient than Javascript, correct? Can someone shed some light on how terrible this would be, efficiency-wise?
It is not impossible to deconstruct the AS3 code within a Flash movie. While it would thwart the casual observer, if someone with skills wanted to get at your scripts they would be able to. You would only be throwing a roadblock in their path, not an impassable one, and possibly one that is even less difficult to crack than the code produced by standard JS obfuscators.
As for performance, Flash execution compares well with browser-hosted Javascript interpreters. See http://jacksondunstan.com/articles/232 for one set of comparisons. It is close to the fastest JS for sheer code execution*.
N.B. — And for graphical UI tasks nothing else (i.e., HTML 5) so far has even come close. This may change with IE9's new JS engine and its hardware acceleration, but it is not clear whether Adobe will be able to tap into the same thing at some point.
Hey all, I'm looking at building an ajax-heavy site, and I'm trying to spend some time upfront thinking through the architecture.
I'm using Code Igniter and jquery. My initial thought process was to figure out how to replicate MVC on the javascript side, but it seems the M and the C don't really have much of a place.
A lot of the JS would be ajax calls BUT I can see it growing beyond that, with plenty of DOM manipulation, as well as exploring the HTML5 clientside database. How should I think about architecting these files? Does it make sense to pursue MVC? Should I go the jquery plugin route somehow? I'm lost as to how to proceed and I'd love some tips. Thanks all!
I've made an MVC style Javascript program. Complete with M and C. Maybe I made a wrong move, but I ended up authoring my own event dispatcher library. I made sure that the different tiers only communicate using a message protocol that can be translated into pure JSON objects (even though I don't actually do that translation step).
So jquery lives primarily in the V part of the MVC architecture. In the M, and C side, I have primarily code which could run in the stand alone CLI version of spidermonkey, or in the serverside rhino implementation of javascript, if necessary. In this way, if requirements change later, I can have my M and C layers run on the serverside, communicating via those json messages to the V side in the browser. It would only require some modifications to my message dispatcher to change this though. In the future, if browsers get some peer to peer style technologies, I could get the different teirs running in different browsers for instance.
However, at the moment, all three tiers run in a single browser. The event dispatcher I authored allows multicast messages, so implementing an undo feature now will be as simple as creating a new object that simply listens to the messages that need to be undone. Autosaving state to the server is a similar maneuver. I'm able to do full detailed debugging and profiling inside the event dispatcher. I'm able to define exactly how the code runs, and how quickly, when, and where, all from that central bit of code.
Of course the main drawback I've encountered is I haven't done a very good job of managing the complexity of the thing. For that, if I had it all to do over, I would study very very carefully the "Functional Reactive" paradigm. There is one existing implementation of that paradigm in javascript called flapjax. I would ensure that the view layer followed that model of execution, if not used specifically the flapjax library. (i'm not sure flapjax itself is such a great execution of the idea, but the idea itself is important).
The other big implementation of functional reactive, is quartz composer, which comes free with apple's developer tools, (which are free with the purchase of any mac). If that is available to you, have a close look at that, and how it works. (it even has a javascript patch so you can prototype your application with a prebuilt view layer)
The main takaway from the functional reactive paradigm, is to make sure that the view doesn't appear to maintain any kind of state except the one you've just given it to display. To put it in more concrete terms, I started out with "Add an object to the screen" "remove an object from the screen" type messages, and I'm now tending more towards "display this list of objects, and I'll let you figure out the most efficient way to get from the current display, to what I now want you to display". This has eliminated a whole host of bugs having to do with sloppily managed state.
This also gets around another problem I've been having with bugs caused by messages arriving in the wrong order. That's a big one to solve, but you can sidestep it by just sending in one big package the final desired state, rather than a sequence of steps to get there.
Anyways, that's my little rant. Let me know if you have any additional questions about my wartime experience.
At the risk of being flamed I would suggest another framework besides JQuery or else you'll risk hitting its performance ceiling. Its ala-mode plugins will also present a bit of a problem in trying to separate you M, V and C.
Dojo is well known for its Data Stores for binding to server-side data with different transport protocols, and its object oriented, lighting fast widget system that can be easily extended and customized. It has a style that helps guide you into clean, well-divisioned code – though it's not strictly MVC. That would require a little extra planning.
Dojo has a steeper learning curve than JQuery though.
More to your question, The AJAX calls and object (or Data Store) that holds and queries this data would be your Model. The widgets and CSS would be your View. And the Controller would basically be your application code that wires it all together.
In order to keep them separate, I'd recommend a loosely-coupled event-driven system. Try to directly access objects as little as possible, keeping them "black boxed" and get data via custom events or pub/sub topics.
JavaScriptMVC (javascriptmvc.com) is an excellent choice for organizing and developing a large scale JS application.
The architecture design is very practical. There are 4 things you will ever do with JavaScript:
Respond to an event
Request Data / Manipulate Services (Ajax)
Add domain specific information to the ajax response.
Update the DOM
JMVC splits these into the Model, View, Controller pattern.
First, and probably the most important advantage, is the Controller. Controllers use event delegation, so instead of attaching events, you simply create rules for your page. They also use the name of the Controller to limit the scope of what the controller works on. This makes your code deterministic, meaning if you see an event happen in a '#todos' element you know there has to be a todos controller.
$.Controller.extend('TodosController',{
'click' : function(el, ev){ ... },
'.delete mouseover': function(el, ev){ ...}
'.drag draginit' : function(el, ev, drag){ ...}
})
Next comes the model. JMVC provides a powerful Class and basic model that lets you quickly organize Ajax functionality (#2) and wrap the data with domain specific functionality (#3). When complete, you can use models from your controller like:
Todo.findAll({after: new Date()}, myCallbackFunction);
Finally, once your todos come back, you have to display them (#4). This is where you use JMVC's view.
'.show click' : function(el, ev){
Todo.findAll({after: new Date()}, this.callback('list'));
},
list : function(todos){
$('#todos').html( this.view(todos));
}
In 'views/todos/list.ejs'
<% for(var i =0; i < this.length; i++){ %>
<label><%= this[i].description %></label>
<%}%>
JMVC provides a lot more than architecture. It helps you in ever part of the development cycle with:
Code generators
Integrated Browser, Selenium, and Rhino Testing
Documentation
Script compression
Error reporting
I think there is definitely a place for "M" and "C" in JavaScript.
Check out AngularJS.
It helps you with your app structure and strict separation between "view" and "logic".
Designed to work well together with other libs, especially jQuery.
Full testing environment (unit, e2e) + dependency injection included, so testing is piece of cake with AngularJS.
There are a few JavaScript MVC frameworks out there, this one has the obvious name:
http://javascriptmvc.com/
I'm not looking for a full implementation, I'm more interested in how they do it. I know they use GWT, but I'd like a more low level answer. Naively, I would start by thinking when you click the popout link they simply open a new window and copy content into it. There are lots of reasons why that won't work out well, so I'm wondering if anyone knows or has ideas on how they do this or how it could be done.
I recently needed to solve exactly this problem in an app. I ended up using this great little jQuery plugin to do the trick: WindowMsg (see link at bottom) While I'm sure there are other ways to accomplish the same task, that plugin does works thusly:
first you create a new child window from your original window using window.open
you save a reference to the window object returned by window.open
you call a library method in the child window that adds a hidden form for the library to store data in
you call a library method in the parent window that uses window.document.forms to populate form fields on the child window (the library abstracts all of this stuff so you wouldn't even know there was a form involved unless you looked at the source) window.document.forms works the same on all major browsers so this abstraction in x-browser compatible
finally, the child window refers back to its parent window using window.opener and can communicate back via a parallel hidden form on the parent
the library implements a convenient helper that takes a callback function to run on each side to make the callback chain easy to deal with
In my experience working with the library, it would have also been quite nice if they had included the JSON 2 lib from JSON.org. Out of the box, WindowMsg only allows you to send string messages between windows, but with some pretty simple use of the JSON 2 lib, I was able to hack it to allow the sending of full JSON objects between windows. I bet more mature libraries (such as whatever google uses) include that kind of serialization and de-serialization baked in.
I am putting this link here because for some reason, the Stack Overflow formatter turns it into an anchor link with no closing tag and I don't want my whole post to be one giant hyperlink!
WindowMsg:
http://www.sfpeter.com/2008/03/13/communication-between-browser-windows-with-jquery-my-new-plugin/
I would say the easiest way would be to have the data stored on the server (which you probably do already), then just have the new window retrieve that data.
Of course that wouldn't persist things like contents of a text-box the user has input, so depending on what the window is for, it may be impractical.. but it's always best to start trying the simplest option!