0

So I'm coming from two years of teaching myself unity/c# and am starting to feel like I have the coding chops to move from an engine to a framework so I have more control over the environment. I've completed the first few steps of first person environment stuff and wanted to split up my code into seperate files. In c# this is very easy, you just include a:

              class className = new className(); 

for whatever class is in the same folder, but it seems to be less easy in javascript to accomplish this. My attempts so far have led to me losing all three.js functionality.

//Edit://This is what I tried from my knowledge of c#:

initializeObjects(scene);// on the native html javascript function   
function initializeObjects(scene){ code referring to 3js scene object}// on the satellite scripts 

but it isn't reacting the way I'd imagine(as in no errors, but no functionality either). I need to figure out how to write to console on a website build. This is all new to me.

is the answer:

var currentMesh = mesh;//?

I don't have time to test it right now.

//end Edit//

Any tips? I will include all code below.

var mesh, floorMesh;

function initializeObjects(scene){

	mesh = new THREE.Mesh(
		new THREE.BoxGeometry(2,2,2, 4, 4, 4),
		new THREE.MeshPhongMaterial({color:'green', wireframe:false})
	);
	mesh.position.y = 2;
	mesh.receiveShadow = true;
	mesh.castShadow = true;
	scene.add(mesh);

	floorMesh = new THREE.Mesh(
		new THREE.PlaneGeometry(100, 100, 10, 10),
		new THREE.MeshPhongMaterial({color:'grey', wireframe:false})
	);
	floorMesh.rotation.x -= Math.PI /2;
	floorMesh.receiveShadow = true;
	scene.add(floorMesh);

	ambientLight = new THREE.AmbientLight('blue', .3);
	scene.add(ambientLight);

	light = new THREE.PointLight('white', 0.8, 18);
	light.position.set(-3, 6, -3);
	light.castShadow = true;
	light.shadow.camera.near = 0.1;
	light.shadow.camera.far = 25;
	light.shadowMapHeight = 2048;
	light.shadowMapWidth = 2048;
	scene.add(ambientLight);

}

function objectUpdate(){
	mesh.rotation.x += 0.01;
	mesh.rotation.y += 0.01;
}

//this is the start of the first person script

var keyboard = {};
var player = { height:1.8, speed:1, turnSpeed:Math.PI * 0.02 };
var camera;

function initializeControls(scene){
	camera = new THREE.PerspectiveCamera (90, window.innerWidth/window.innerHeight, 0.1, 1000);
	camera.position.set(0, player.height,-4);
	camera.lookAt(new THREE.Vector3(0,player.height,0));
	scene.add(camera);
}

function checkInput(){

	if(keyboard[87]){
		camera.position.x -= Math.sin(camera.rotation.y) * player.speed;
		camera.position.z -= -Math.cos(camera.rotation.y) * player.speed;
	}

	if(keyboard[83]){
		camera.position.x += Math.sin(camera.rotation.y) * player.speed;
		camera.position.z += -Math.cos(camera.rotation.y) * player.speed;
	}

	if(keyboard[65]){
		camera.position.x += Math.sin(camera.rotation.y + Math.PI/2) * player.speed;
		camera.position.z += -Math.cos(camera.rotation.y + Math.PI/2) * player.speed;
	}

	if(keyboard[68]){
		camera.position.x += Math.sin(camera.rotation.y - Math.PI/2) * player.speed;
		camera.position.z += -Math.cos(camera.rotation.y - Math.PI/2) * player.speed;
	}

	if(keyboard[37]){
		camera.rotation.y -= player.turnSpeed;
	}

	if(keyboard[39]){
		camera.rotation.y += player.turnSpeed;
	}
}

function keyDown(event){
	keyboard[event.keyCode] = true;
}

function keyUp(event){
	keyboard[event.keyCode] = false;
}	

window.addEventListener('keydown', keyDown);
window.addEventListener('keyup', keyUp);
<script src="https://github.com/mrdoob/three.js/blob/dev/build/three.min.js"></script>
<!DOCTYPE html>
<html>
	<head>
		<title>Demo 1</title>
		<meta charset="UTF-8"> 
		<style>

			body {
				background-color: #000000;
				margin: 0px;
				overflow: hidden;
			}

			a {
				color:#0078ff;
			}
		</style>

		<script type="text/javascript" src = "https://github.com/mrdoob/three.js/blob/dev/build/three.min.js"></script>
		<script type="text/javascript" src = "objectManager.js"></script>
		<script type="text/javascript" src = "firstPersonController.js"></script>
		
	</head>
	<body>

	</body>
	<script>
		var scene, renderer;

		function init(){
			scene = new THREE.Scene();
					
			renderer = new THREE.WebGLRenderer({antialias: true});
			renderer.setSize(window.innerWidth, window.innerHeight);

			initializeControls(scene);
			initializeObjects(scene);

			renderer.shadowMap.enabled = true;
			renderer.shadowMapSoft = true;
			renderer.shadowMapType = THREE.PCFSoftShadowMap;

			document.body.appendChild(renderer.domElement);
			updateRenderer();
		}

		function updateRenderer(){
			requestAnimationFrame(updateRenderer);
			checkInput();
			objectUpdate();
		}
		window.onload = init();

		</script>
</html>

4
  • Short answer: this is even easier in JavaScript than C# as JavaScript has no restrictions on how to structure sub-modules. Longer answer: vomiting up a ton of code like this and asking us to find the needle in the haystack is unlikely to get much response. What console errors are you getting? Have you stepped through it in the debugger? Where did you break up the code at? etc, etc. Most important answer: application architecture is both too complicated and opinionated to make a good SO answer. Oct 13, 2016 at 18:42
  • Thanks for responding. I'm new here (unity3d questions here and there) so I'm still learning what proper posting procedure is. response to short answer: so how do you reference it in code? response to long answer: I just thought people might try to test the code or something, like I said, I'm new here. I did some editing to try and add the things you said to the original post.
    – Lawrence
    Oct 13, 2016 at 19:04
  • 1
    You're hotlinking from the github blob/page rather than the actual source file: e.g., github.com/mrdoob/three.js/blob/dev/build/three.min.js (No) vs. github.com/mrdoob/three.js/raw/dev/build/three.min.js (Yes). Btw, word of advice: pull the full threejs subrepo into your project rather than hotlinking -- otherwise your project is likely to break as updates are made to threejs/dev
    – msun
    Oct 13, 2016 at 19:11
  • I was actually trying to edit the code so ya'll could run it from this thread, but you're right; I'm a total noob when it comes to that sort of stuff so I'm mucking it all up.
    – Lawrence
    Oct 13, 2016 at 19:16

3 Answers 3

0

JavaScript does not (yet) have an implemented native module system. Its been ratified, but not implemented. Leaving you a few different options:

Option 1: Global namespace variables, aka the Revealing Module Pattern:

This is a pretty common approach. Looks like this in code:

// top-level name declaration
window.myNamespace = (function() {
  // internal implementation stuff goes here
  return {
    // public API goes here, for example
    fooMethod: function (n) {
      return n + 'foo';
    }
  };
})();

Then in another file you can just say

// remember myNamespace is a global variable.
myNamespace.fooMethod('bar'); // 'barfoo' 

This has a couple of disadvantages though. First, if you're using a lot of third-party libraries there's a pretty good chance of a name collision. This is particularly true if the code modifies a global object like Array or Object. It also requires a fair amount of effort from the developer to maintain.

Option 2 Third party module system. See this for a more in-depth discussion.

6
  • So what you are saying is that most people just make ridiculously long javascript code for this reason? Just making sure I understand what you are saying.
    – Lawrence
    Oct 13, 2016 at 19:18
  • my goal is a simple game engine, so I want it to be organized elegantly as there is going to be alot of different functionality eventually.
    – Lawrence
    Oct 13, 2016 at 19:20
  • No, I'm saying with great power comes great responsibility. JavaScript lets you create global variables anywhere: every single top-level var is a global variable. C# tries to hold your hand by making global variable creation difficult. Which is preferable is a matter of taste, but if you want to avoid name collisions in JavaScript you wrap your modules in IIFEs (or use a module library that does it for you). Oct 13, 2016 at 19:26
  • I find having to wrap EVERY function in a class and EVERY global variable in a singleton to be 'ridiculously long'. Oct 13, 2016 at 19:28
  • I don't find that to be true yet but I'm sure there is something I'm missing. For example: I'm currently using visual studio and when I type "mesh" into a function on firstPersonController.js no intellisense picks it up. (although it does outside of the functions I see now, which you might be implying is part of the answer I'm looking for)
    – Lawrence
    Oct 13, 2016 at 19:32
0

In Js only functions create a new scope, but global stuff is available everywhere. Classes and inheritance is different to most other languages.

Tutorials: scoping, Prototypal inheritance. Google will give you more infos.

By the way, you defined var keyboard = {}; and later used keyboard as array.

0

So ultimately what I did (this is contingent on the website thing I think, I wouldn't know how javascript compiles besides a website at this point) is put all of the variables on the first loaded script. It's definitely confusing to think about as a c# coder, but that was the thing that made everything work, and then from there I just broke up the code exactly as it was written already and placed it on separate files. It's working like a charm and I'm ready to start working through more functionality. Wanted to mark one of the answer's right, but there was a few extra steps I needed to take with the information I was given. Thanks everyone for your help.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.