Jump to content
  • Advertisement

Introduction to THREE.js

Awoken

705 views

Time to introduce just how awesome THREE.js is. 
With the following three files you too can begin building content with THREE.js that will work in any browser that supports WebGL.The files include the latest and greatest minified version of THREE.js.
three.min.js

Out of the box code to begin this project.

var camera, scene, renderer;
var geometry, material, mesh;

init();
animate();

function init() {

	camera = new THREE.PerspectiveCamera( 70, 1024 / 768 , 0.01, 10 );
	camera.position.z = 1;

	scene = new THREE.Scene();

	geometry = new THREE.BoxGeometry( 0.2, 0.2, 0.2 );
	material = new THREE.MeshNormalMaterial();

	mesh = new THREE.Mesh( geometry, material );
	scene.add( mesh );

	renderer = new THREE.WebGLRenderer( { antialias: true } );
	renderer.setSize( 1024 , 768 );
	document.body.appendChild( renderer.domElement );

}

function animate() {

	requestAnimationFrame( animate );

	mesh.rotation.x += 0.01;
	mesh.rotation.y += 0.02;

	renderer.render( scene, camera );

}

shapesTD.js

And a basic html file which references both THREE.js and the basic code for starting this project.

<html>
	<head>

    	<title>Shapes TD</title>

	</head>
	<body oncontextmenu="return false;">

		<script src='three.min.js'></script>
		<script src='shapesTD.js'></script>

	</body>
</html>

ShapesTD.html
 

Once you click on the html file with both of the other files in the same directory you should see a spinning cube.
cube.png.18d4ba2681dec815fab1f1e01c01cbb6.png

If not, check to see if you have WebGL support enabled on the browser you are using.  


This will be my starting base.  I figured I'd throw in the code as well so that if any beginner wants to have a shot at an extremely easy language, JavaScript, and a well documented API, then these files are for you.

 



3 Comments


Recommended Comments

Thanks for posting! :) I've never used WebGL before, and even had to turn down a client project at one time because they wanted a 3D JavaScript application. This is something on my bucket list to learn in the future.

Share this comment


Link to comment

I've heard good things about three.js, looks relatively simple!

Share this comment


Link to comment

Hi,

I rewrote your example in TypeScript.

Playground

intro-to-threejs.zip

Program.ts

import { MyScene } from "./MyScene";

export class Program
{
    public static main()
    {
        let scene = new MyScene();
        scene.Init();
        scene.Animate();
    }
}

Program.main();

MyScene.ts

import * as THREE from "three";

export class MyScene
{
    private _camera: THREE.PerspectiveCamera;
    private _scene: THREE.Scene;
    private _mesh: THREE.Mesh;
    private _renderer: THREE.WebGLRenderer;

    public constructor()
    {
        this._camera = new THREE.PerspectiveCamera(
            70, window.innerWidth / window.innerHeight, 0.01, 10);
        this._scene = new THREE.Scene();

        let geometry = new THREE.BoxGeometry(0.2, 0.2, 0.2);
        let material = new THREE.MeshNormalMaterial();
        this._mesh = new THREE.Mesh(geometry, material);

        this._renderer = new THREE.WebGLRenderer({ antialias: true });
    }

    public Animate(): void
    {
        requestAnimationFrame(() => this.Animate());

        this._mesh.rotation.x += 0.01;
        this._mesh.rotation.y += 0.01;

        this._renderer.render(this._scene, this._camera);
    }
    public Init(): void
    {
        this._camera.position.z = 1;
        this._scene.add(this._mesh);
        this._renderer.setSize(window.innerWidth, window.innerHeight);
        document.body.appendChild(this._renderer.domElement);
    }
}

 

Edited by 8Observer8

Share this comment


Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Advertisement
  • Advertisement
  • Blog Entries

  • Similar Content

    • By Val Valentino
      I've developed a browser game that I do not intend to sell and I'm looking for an investor to help me with advertising and upgrading.
      Languages: PHP7, HTML, JS, Jquery
      Database: MySQL
      FrameWork: Laravel
      Anyone who wants more information, write on PM
    • By niamleeson
      Dear Gamedev.net members,
      I'm sorry to be asking in Javascript, but it is the only language I'm working with currently. I am hoping that the code is simple enough for you to understand what it is doing.
      I'm trying to rotate a cube so that dragging down always rotates the object around the world X axis, and dragging to the side always rotates the object around the world Y axis no matter the rotation of the object.
      I've seen this example which achieves the exact behavior I am looking for: https://jsfiddle.net/MadLittleMods/n6u6asza/
      And then, here's my jsFiddle code that I'm having trouble with: http://jsfiddle.net/9sqvp52u/
      I saw this stackoverflow answer: https://stackoverflow.com/questions/45091505/opengl-transforming-objects-with-multiple-rotations-of-different-axis
      But I still don't understand what I'm doing wrong. I think I'm still multiplying the rotation matrix to the left side of the object matrix in my code, but the object is always just rotating around its local axis. I learned how the transformation matrix works and how quaternion works but I feel like I am still missing something crucial here.
      I would really appreciate your help.
      Thank you.
    • By Steffi
      I am creating an endless runner, please see my code here: https://codepen.io/clownhead/pen/BqyqOm
      At the moment when the left arrow key is pressed the player moves left, the camera follows him so he does not go off screen and the ground tiles below the player are destroyed as they move out of the world bounds on the right and are recreated just before they move into the world bounds on the left. This allows him to keep running forever without running out of ground and works perfectly, but with one problem: I want the player to be running to the right of the game, NOT to the left. Please note I do not need the player to be able to move both ways. I can make the camera follow the player to the right instead of the left by doing the following: I remove the negative from -this in
      this.world.setBounds(-this.player.xChange, 0, ...); so it becomes
      this.world.setBounds(this.player.xChange, 0, ...); Now when the right arrow key is pressed the camera follows the player as he runs right so he does not go off screen, but the ground tiles do not regenerate and he runs out of ground. So basically I need to reverse the direction in which the ground is regenerating but I can't figure out how to do it.  As everything is working to the left, I am sure it's a few simple settings, perhaps some negatives that need to be made positive? I have tried all that I can think of but I can't get it to work. I think the key to solving this might be in these lines:
      this.platforms.forEachAlive( function( elem ) { this.platformXMin = Math.min( this.platformXMin, elem.x ); if( elem.x > this.camera.x + this.game.width ) { elem.kill(); this.platformsCreateOne( this.platformXMin - 70, this.world.height - 50, 50 ); } }, this ); I have tried changing all sorts of settings there, but I can't seem to get it to work. I am new to Phaser and still learning Javascript. Is anyone able to see an obvious solution? I'd be so grateful. Thanks in advance for any help!
    • By Steffi
      I have a background image and a separate ground image that I want to repeat as long as the character is moving forward. When the character stops, the background and ground should not be moving. Basically I am creating an endless runner. For similar games it is often suggested to add this.game.background.tilePosition.x -= 1to the update function. This is not what I am looking for as it makes the background constantly move regardless of whether the character is moving. At the moment my background and ground images are repeating, but they are restricted to this.game.world.setBounds(0, 0, 1280, 800);. Any suggestions would be greatly appreciated as I have been at this for days, and I am sure there must be a simple solution. Please see my code below:
       
      function Hero(game, x, y) { Phaser.Sprite.call(this, game, x, y, 'player'); this.anchor.set(0.5, 0.5); this.game.physics.enable(this); this.body.collideWorldBounds = false; this.animations.add('stop', [0]); this.animations.add('run', [1, 2, 3, 4, 5], 14, true); // 14fps looped this.animations.add('jump', [6]); this.animations.add('fall', [7]); this.animations.add('die', [8, 9, 8, 9, 8, 9, 8, 9], 12); // 12fps no loop } Hero.prototype = Object.create(Phaser.Sprite.prototype); Hero.prototype.constructor = Hero; Hero.prototype.move = function (direction) { const SPEED = 200; this.body.velocity.x = direction * SPEED; if (this.body.velocity.x < 0) { this.scale.x = -1; } else if (this.body.velocity.x > 0) { this.scale.x = 1; } }; Hero.prototype.jump = function () { const JUMP_SPEED = 600; let canJump = this.body.touching.down; if (canJump) { this.body.velocity.y = -JUMP_SPEED; } return canJump; }; Hero.prototype.bounce = function () { const BOUNCE_SPEED = 200; this.body.velocity.y = -BOUNCE_SPEED; }; Hero.prototype.update = function () { // update sprite animation, if it needs changing let animationName = this._getAnimationName(); if (this.animations.name !== animationName) { this.animations.play(animationName); } }; Hero.prototype.die = function () { this.alive = false; this.body.enable = false; this.animations.play('die').onComplete.addOnce(function () { this.kill(); }, this); }; Hero.prototype._getAnimationName = function () { let name = 'stop'; // default animation if (!this.alive) { name = 'die'; } else if (this.body.velocity.y > 0 && !this.body.touching.down) { name = 'fall'; } else if (this.body.velocity.y < 0) { name = 'jump'; } else if (this.body.velocity.x !== 0 && this.body.touching.down ) { name = 'run'; } return name; PlayState = {}; PlayState.init = function () { this.game.renderer.renderSession.roundPixels = true; this.keys = this.game.input.keyboard.addKeys({ left: Phaser.KeyCode.LEFT, right: Phaser.KeyCode.RIGHT, up: Phaser.KeyCode.UP }; PlayState.preload = function () { this.game.load.json('level:1', 'data/level01.json'); this.game.load.image('ground', 'images/ground.png'); // I need this to repeat infinitely this.game.load.image('background', 'images/background.png'); // I need this to repeat infinitely this.game.load.spritesheet('player', 'images/player.png', 64, 64); }; PlayState.create = function () { this.game.world.setBounds(0, 0, 1280, 800); this.game.background = this.game.add.tileSprite(0, 0, this.game.world.width, 800, 'background'); this.game.ground = this.game.add.tileSprite(0, 680, this.game.world.width, 166, 'ground'); this.game.physics.arcade.enable(this.game.ground); this.game.ground.body.immovable = true; this.game.ground.body.allowGravity = false; this.game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL; this._loadLevel(this.game.cache.getJSON('level:1')); }; PlayState.update = function () { this.physics.arcade.collide(this.player, this.game.ground); this._handleInput(); }; PlayState._handleInput = function () { if (this.keys.up.isDown) { this.player.jump(); } else if (this.keys.right.isDown) { // move player right this.player.move(1); } else if (this.keys.left.isDown) { // move player left this.player.move(-1); } else { // stop this.player.move(0); } }; PlayState._loadLevel = function (data) { this._spawnPlayer({player: data.player}); const GRAVITY = 1200; this.game.physics.arcade.gravity.y = GRAVITY; }; PlayState._spawnPlayer = function (data) { this.player = new Hero(this.game, data.player.x, data.player.y); this.game.add.existing(this.player); this.game.camera.follow(this.player, Phaser.Camera.FOLLOW_PLATFORMER); }; window.onload = function () { let game = new Phaser.Game(866, 520, Phaser.CANVAS, 'game'); game.state.add('play', PlayState); game.state.start('play'); };  
    • By MakeIndieGreatAgain
      Game developers will be able to become pioneers in the development of decentralized games for the gambling industry using DAO.Casino protocol.
      On September 17, 2018, DAO.Casino is opening Sandbox for developers, independent teams and game development studios that choose to harness the power of the rapidly developing DApp industry.
      Starting today everyone may submit their application for Sandbox on the official Sandbox page.
      The Sandbox project is designed by DAO.Casino developers. Participants of Sandbox will learn the basics of decentralized applications development on DAO.Casino protocol. Developers participating in Sandbox will learn to create, design and deploy decentralized games and applications on Ethereum blockchain.
      DAO.Casino is planning to reward most active developers for their constructive feedback on the improvement and optimization of the SDK and related documentation. The company will separately announce the details of the rewards program later this fall.
      “We are confident that the Sandbox project will play an important role in our collaboration with studios and independent game developers. We cannot wait to see our product helping developers unleash their creative and entrepreneurial talents and apply those to one of the most groundbreaking technologies of the XXI century. — states Ilya Tarutov, CEO, DAO.Casino. – I am sure that the products we’re developing will transform the online gambling into a fair and transparent industry for all of the involved parties: casino operators, developers, and affiliate marketers. “
      “We are launching the Sandbox with the goal of enabling as many developers as possible to learn to create decentralized games. We have achieved an important milestone by starting to accept applications from developers all around the world who share our idea to make online gambling fair and transparent. With our technology, developers can take the whole gambling industry to the next level” – says Alexandra Fetisova from DAO.Casino.
      DAO.Casino is disrupting the online gambling industry by developing the protocol based on Ethereum blockchain technology. The protocol ensures the automation of transactions and facilitates interactions between all the industry participants: casino operators, game developers, and affiliate marketers. DAO.Casino team is fully dedicated to developing the best products and making the gambling industry a better place.

      View full story
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!