Letter O
Letter X
How to make a tic tac toe game using only context.save/context.restore, if statements, canvas, and animations? I'm also trying to make it so that if image X is displayed in box 1, image O can't be displayed in the same box so you can't cheat.
I do not know how to prevent someone to put image O on image X, vice versa. Please, someone, show me a way to prevent people to place an O on top of an X and vice versa.
This is what I have so far
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
<link rel="stylesheet" href="U1TS.css">
</head>
<body>
<canvas id="canvas" width="400" height="400"></canvas>
<br>
<button onclick="Restart()">Restart</button>
<script type="text/javascript">
var canvas = document.getElementById("canvas");
var context = canvas.getContext('2d');
var c1 = 1
var c2 = 1
var c3 = 1
var c4 = 1
var c5 = 1
var c6 = 1
var c7 = 1
var c8 = 1
var c9 = 1
var cup1 = 2
var cup2 = 2
var cup3 = 2
var cup4 = 2
var cup5 = 2
var cup6 = 2
var cup7 = 2
var cup8 = 2
var cup9 = 2
//Line horizontale et verticale
context.beginPath();
context.moveTo(40,145);
context.lineTo(360,145);
context.lineWidth = 5
context.lineCap = 'round';
context.stroke();
context.beginPath();
context.moveTo(40,260);
context.lineTo(360,260);
context.lineCap = 'round';
context.stroke();
context.beginPath();
context.moveTo(260,40);
context.lineTo(260,360);
context.lineCap = 'round';
context.stroke();
context.beginPath();
context.moveTo(140,40);
context.lineTo(140,360);
context.lineCap = 'round';
context.stroke();
context.font = "italic bold 30pt Calibri"
context.fillText("1", 75, 325);
context.fillText("2", 190, 325);
context.fillText("3", 305, 325);
context.fillText("4", 75, 215);
context.fillText("5", 190, 215);
context.fillText("6", 305, 215);
context.fillText("7", 75, 105);
context.fillText("8", 190, 105);
context.fillText("9", 305, 105);
function Restart(){
document.location.reload(true);
}
document.onkeydown = Nombre;
Nombreup1 = 49; Nombreup2 = 50; Nombreup3 = 51;
Nombreup4 = 52; Nombreup5 = 53; Nombreup6 = 54;
Nombreup7 = 55; Nombreup8 = 56; Nombreup9 = 57;
Nombre7 = 103; Nombre8 = 104; Nombre9 = 105;
Nombre4 = 100; Nombre5 = 101; Nombre6 = 102;
Nombre3 = 99; Nombre2 = 98; Nombre1 = 97;
function Nombre(e){
toucheCourante = e.keyCode;
if (toucheCourante == Nombre7){
lettreO7();
} else if (toucheCourante == Nombre8){
lettreO8();
} else if (toucheCourante == Nombre9){
lettreO9();
} else if (toucheCourante == Nombre6){
lettreO6();
} else if (toucheCourante == Nombre5){
lettreO5();
} else if (toucheCourante == Nombre4){
lettreO4();
} else if (toucheCourante == Nombre3){
lettreO3();
} else if (toucheCourante == Nombre2){
lettreO2();
} else if (toucheCourante == Nombre1){
lettreO1();
}
/////////////////////////////////////////
if (toucheCourante == Nombreup7){
lettreX7();
} else if (toucheCourante == Nombreup8){
lettreX8();
} else if (toucheCourante == Nombreup9){
lettreX9();
} else if (toucheCourante == Nombreup6){
lettreX6();
} else if (toucheCourante == Nombreup5){
lettreX5();
} else if (toucheCourante == Nombreup4){
lettreX4();
} else if (toucheCourante == Nombreup3){
lettreX3();
} else if (toucheCourante == Nombreup2){
lettreX2();
} else if (toucheCourante == Nombreup1){
lettreX1();
}
}
function lettreO1()
{
lettreO = new Image();
lettreO.src = 'O.jpg';
lettreO.onload = function(){
context.drawImage(lettreO, 40, 265,95,93);
}
}
function lettreX1()
{
lettreX = new Image();
lettreX.src = 'X.PNG';
lettreX.onload = function(){
context.drawImage(lettreX, 40, 265,95,93);
}
}
function lettreO2()
{
lettreO = new Image();
lettreO.src = 'O.jpg';
lettreO.onload = function(){
context.drawImage(lettreO, 145, 265,110,93);
}
}
function lettreX2()
{
lettreX = new Image();
lettreX.src = 'X.PNG';
lettreX.onload = function(){
context.drawImage(lettreX, 145, 265,110,93);
}
}
function lettreO3()
{
lettreO = new Image();
lettreO.src = 'O.jpg';
lettreO.onload = function(){
context.drawImage(lettreO, 265, 265,95,93);
}
}
function lettreX3()
{
lettreX = new Image();
lettreX.src = 'X.PNG';
lettreX.onload = function(){
context.drawImage(lettreX, 265, 265,95,93);
}
}
function lettreO4()
{
lettreO = new Image();
lettreO.src = 'O.jpg';
lettreO.onload = function(){
context.drawImage(lettreO, 40,149,95,107);
}
}
function lettreX4()
{
lettreX = new Image();
lettreX.src = 'X.PNG';
lettreX.onload = function(){
context.drawImage(lettreX, 40,149,95,107);
}
}
function lettreO5()
{
lettreO = new Image();
lettreO.src = 'O.jpg';
lettreO.onload = function(){
context.drawImage(lettreO, 145,149,110,107);
}
}
function lettreX5()
{
lettreX = new Image();
lettreX.src = 'X.PNG';
lettreX.onload = function(){
context.drawImage(lettreX, 145,149,110,107);
}
}
function lettreO6()
{
lettreO = new Image();
lettreO.src = 'O.jpg';
lettreO.onload = function(){
context.drawImage(lettreO, 265,149,95,107);
}
}
function lettreX6()
{
lettreX = new Image();
lettreX.src = 'X.PNG';
lettreX.onload = function(){
context.drawImage(lettreX, 265,149,95,107);
}
}
function lettreO7()
{
lettreO = new Image();
lettreO.src = 'O.jpg';
lettreO.onload = function(){
context.drawImage(lettreO, 40,40,95,101);
}
}
function lettreX7()
{
lettreX = new Image();
lettreX.src = 'X.PNG';
lettreX.onload = function(){
context.drawImage(lettreX, 40,40,95,101);
}
}
function lettreO8()
{
lettreO = new Image();
lettreO.src = 'O.jpg';
lettreO.onload = function(){
context.drawImage(lettreO, 145,40,110,101);
}
}
function lettreX8()
{
lettreX = new Image();
lettreX.src = 'X.PNG';
lettreX.onload = function(){
context.drawImage(lettreX, 145,40,110,101);
}
}
function lettreO9()
{
lettreO = new Image();
lettreO.src = 'O.jpg';
lettreO.onload = function(){
context.drawImage(lettreO, 265,40,95,101);
}
}
function lettreX9()
{
lettreX = new Image();
lettreX.src = 'X.PNG';
lettreX.onload = function(){
context.drawImage(lettreX, 265,40,95,101);
}
}
</script>
</body>
</html>
We talked in the chat, but since I don't know when we will be on SO at the same time, I'm posting a solution. I still can help you step by step if you want to.
First, I cleaned and simplified some parts of your code to avoid to much work:
I put all the code designed to draw the grid in a drawGrid(context) function:
From:
// Line horizontale et verticale
To:
context.fillText("9", 305, 105);
Then, I rewrote the function Nombre(e) {...} function.
I used a keyboard map:
var KEYBOARD = {
NUMBER_UP_1: 49,
...
NUMBER_UP_9: 57,
NUMBER_1: 97,
...
NUMBER_9: 105,
};
I renamed the function function onKeyDown(e) {...}, because Nombre(e) isn't very explicit and may be confused with the Number(n) function.
I deduced the letter from the keyCode. It's an X if the keyCode is in [49, ..., 57], or an O if the keyCode is in [97, ..., 105].
Then, the calculation keyCode - {firstKeyCodeForCurrentLetter} - 1 gives you the number on the pressed key. For example, if you press 50, you have: 50 - 49 + 1 = 2, and according to the keyboard map, 50 is associated with the key UP_2.
Then, whenever a number key is pressed (except 0), I check if any player has already played here. I created a letterAt(memoryContext, position) function that returns true if a player has already played at the position, false otherwise. If the player hasn't, then I save the move with a memorizeMove(memoryContext, letter, position) that draws in the memoryCanvas, then I update the main canvas by draw either an X or a O on it.
Finally, I determine if there is a winner with a winOrLoss(memoryContext) function that returns either a letter: 'O' or 'X', or an empty string '' if there's no winner yet.
I didn't handle the draw nor the fact that each player must wait his turn to play. So a player can play twice in a row. But that's something you can fix. There isn't any proper game over either: if a player wins, there's an alert, that's all, the game can still continue after that.
But the restart() works: I initialized everything we needed in this function, so that every time it's called, it clears both canvases and initializes variables.
I also rewrote the lettreX1(), lettreO3() and so on, functions because: no need to load the same image each time you want to draw. Load once and use as many times as you want. Then, you just have to give the x,y position to a function to draw the image where you want, reducing your 18 functions to only one.
To save the game's state, you didn't want to use variables (like an array or a matrix to know which moves has already been played for instance), so we agreed to use a secondary canvas. This canvas is 3x3 in size. Each time a player plays, if the move is allowed, then we draw one pixel of this canvas, which indicates that the position isn't empty anymore. A player a color. I did this with the memorizeMove(memoryContext, letter, position) function:
function memorizeMove(memoryContext, letter, position) {
memoryContext.fillStyle = letter === `O` ? 'red' : 'blue';
var coords = getCoordinatesFromPosition(position);
memoryContext.fillRect(coords.x, coords.y, 1, 1);
}
It sets the color according to the player's letter (O -> red, X -> blue), gets the x,y coordinates from the position in the grid, then draws a pixel, that is to say a 1x1 rectangle, at this position with the set color.
To check if a move is allowed, I use the letterAt(memoryContext, position) function, which converts the pixel color (red, blue or blank) into a letter or an empty string. I could have just return true or false, but I needed the letters in the winOrLoss(memoryContext) function, and I thought that it may also be useful later to know which player has played here, if any.
function letterAt(memoryContext, position) {
var color = getPixelAt(memoryContext, position);
return color === 'red'
? 'O'
: color === 'blue'
? 'X'
: '';
}
It uses a getPixelAt(memoryContext, position) that returns the pixel's color on the memoryContext of the 2nd canvas at the specified position, as seen together. It converts the position into x,y coordinates, then gets the pixel at x,y, gets its RGBA colors and returns its color.
function getPixelAt(memoryContext, position) {
var coords = getCoordinatesFromPosition(position);
var pixel = memoryContext.getImageData(coords.x, coords.y, 1, 1);
var data = pixel.data;
var red = data[0];
var blue = data[2];
var color = '';
if (red === 255) {
color = 'red';
} else if (blue === 255) {
color = 'blue';
}
return color;
}
I was a bit lazy when I wrote the getCoordinatesFromPosition(position) function... In fact, you're supposed to use a combination of % and / but since your grid is inverted (top-left is a 7, not a 1), I thought that it might be trickier than expected, so I made something very simple instead, with ifs only.
function getCoordinatesFromPosition(position) {
var x = [1, 4, 7].includes(position)
? 0
: [2, 5, 8].includes(position)
? 1
: 2;
var y = position < 4
? 2
: position < 7
? 1
: 0;
return { x: x, y: y };
}
Lastly, for the winOrLoss(memoryContext) function, I read the canvas using the letterAt(memoryContext, i) function and store them in an array. Then I compared the letters between each others, horizontally, vertically and in diagonal, looking for 3 identical letters. It returns true if the condition is met, false otherwise.
function winOrLoss(memoryContext) {
var letters = [];
for (var i = 1; i <= 9; i++) {
letters.push(letterAt(memoryContext, i));
}
if (letters[0] === letters[1] && letters[1] === letters[2] && letters[0] !== ''
|| letters[3] === letters[4] && letters[4] === letters[5] && letters[3] !== ''
|| letters[6] === letters[7] && letters[7] === letters[8] && letters[6] !== ''
|| letters[0] === letters[3] && letters[3] === letters[6] && letters[0] !== ''
|| letters[1] === letters[4] && letters[4] === letters[7] && letters[1] !== ''
|| letters[2] === letters[5] && letters[4] === letters[8] && letters[2] !== ''
|| letters[0] === letters[4] && letters[4] === letters[8] && letters[0] !== ''
|| letters[2] === letters[4] && letters[4] === letters[7] && letters[2] !== ''
) {
return letters[0];
}
}
As usual, here's the fiddle: https://jsfiddle.net/nmerinian/2h87Ltr9/75/
I am trying out the following using three.js, where I have 2 shapes: “squares” and a “sphere”.
Each object has a button associated with it. If the user clicks a button, the corresponding shape will be added to the scene however, there can only be 1 square and 1 sphere in a scene at any one time.
If the user adds a new square, it should replace the old one. I seem to be having trouble achieving this though with my code below. Currently, I can successfully add the square and sphere objects however, when I click to add another square, the current square doesn’t get replaced.
Please advise, thank you!
<html>
<head>
<title>My second three.js app</title>
<style>
body { margin: 0; }
canvas { width: 100%; height: 100% }
</style>
</head>
<body>
<button id="button1">Square1</button>
<button id="button2">Square2</button>
<button id="button3">Sphere</button>
<script src="js/three.js"></script>
<script>
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
loader.load( ‘square1.glb’, function ( geometry ) {
geometry.scene.traverse( function ( node ) {
if ( node.isMesh ){
square = node;
square.material.map.anisotropy = maxAnisotropy;
}
document.getElementById("button1").addEventListener("click", function(){
scene.remove(square);
scene.add(square);
});
});
loader.load( ‘square2.glb’, function ( geometry ) {
geometry.scene.traverse( function ( node ) {
if ( node.isMesh ){
square = node;
square.material.map.anisotropy = maxAnisotropy;
}
document.getElementById("button2").addEventListener("click", function(){
scene.remove(square);
scene.add(square);
});
});
loader.load( ‘sphere.glb’, function ( geometry ) {
geometry.scene.traverse( function ( node ) {
if ( node.isMesh ){
sphere = node;
sphere.material.map.anisotropy = maxAnisotropy;
}
document.getElementById("button3").addEventListener("click", function(){
scene.add(sphere);
});
});
var animate = function () {
requestAnimationFrame( animate );
renderer.render( scene, camera );
};
animate();
</script>
</body>
</html>
Consider tracking the "current square" shape outside the scope of your <button> click handlers, to ensure that the logic for adding and removing these shape from the scene functions as expected.
Specifically, you'll want to call scene.remove() with the current square shape (if present), rather than to call it with the shape object that you subsequently call scene.add() with:
/* Current code */
document.getElementById("button1").addEventListener("click", function(){
scene.remove(square); /* You're removing the square object here, */
scene.add(square); /* and then adding the same square object to the scene */
});
You might find it useful to adapt your script as follows:
var scene = new THREE.Scene();
var camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );
var renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );
/*
Not sure where you get your loader object from
*/
var loader = ''; // ??
/*
Add this to track current shapes
*/
var currentSquare = '';
var currentSphere = '';
/*
Define a general, reusable method for loading geometry
*/
function loadShape(filename, onLoaded) {
loader.load( filename, function ( geometry ) {
var foundMesh = '';
geometry.scene.traverse( function ( node ) {
if ( node.isMesh ){
foundMesh = node;
foundMesh.material.map.anisotropy = maxAnisotropy;
}
});
if(foundMesh) {
onLoaded(foundMesh)
}
}
}
/*
Use the general loader method defined above
*/
loadShape('square1.glb', function(nextSquare) {
document.getElementById("button1").addEventListener("click", function(){
/*
If current square exists, remove it
*/
if(currentSquare) {
scene.remove(currentSquare);
}
/*
Add the square for the button just clicked
and update currentSquare
*/
scene.add(nextSquare);
currentSquare = nextSquare;
});
})
loadShape('square2.glb', function(nextSquare) {
document.getElementById("button2").addEventListener("click", function(){
if(currentSquare) {
scene.remove(currentSquare);
}
scene.add(nextSquare);
currentSquare = nextSquare;
});
})
loadShape('sphere.glb', function(nextSphere) {
document.getElementById("button3").addEventListener("click", function(){
if(currentSphere) {
scene.remove(currentSphere);
}
scene.add(nextSphere);
currentSphere = nextSphere;
});
})
var animate = function () {
requestAnimationFrame( animate );
renderer.render( scene, camera );
};
animate();
Hope this helps!
I tried loading my .obj and .mtl files and now I'm trying to change the material of the object on keypress, I'm able to do changes as expected using texture images. However when I want to change materials using a phong effect with or without texture image it's not happening.
//THIS METHOD IS WORKING FINE WHEN I USE BASIC TEXTURE IMAGES ON KEYPRESS
var texture1 = THREE.ImageUtils.loadTexture("neavik/9.jpg");
var texture2 = THREE.ImageUtils.loadTexture("neavik/10.jpg");
if (child.material.name == "meta") {
child.material.map = texture1;
child.material.needsUpdate = true;
child.receiveShadow = true;
var index = 0;
var onKeyDown = function(event) {
if (event.keyCode == 67) { // when 'c' is pressed
object.traverse(function(child) {
if (child instanceof THREE.Mesh) {
var colors = [texture2, texture1];
if (child.material.name == "meta") {
if (index == colors.length) index = 0;
child.material.map = colors[index++];
child.material.needsUpdate = true;
child.geometry.buffersNeedUpdate = true;
child.geometry.uvsNeedUpdate = true;
}
}
}
};
document.addEventListener('keyup', onKeyDown, true);
});
// Now if i try to change materials with same effect like PHONG it doesn't reflect any changes on Keypress.[ No errors as well ]
var texture1 = THREE.ImageUtils.loadTexture("neavik/9.jpg");
var texture2 = THREE.ImageUtils.loadTexture("neavik/10.jpg");
var cleana = new THREE.MeshPhongMaterial({
map: texture1,
color: 0xffffef,
specular: 0x000000,
combine: THREE.AddOperation,
reflectivity: 0
})
var cleanb = new THREE.MeshPhongMaterial({
map: texture2,
color: 0xffffef,
specular: 0x000000,
combine: THREE.AddOperation,
reflectivity: 0
})
if (child.material.name == "meta") {
child.material = cleana;
child.material.needsUpdate = true;
child.receiveShadow = true;
var index = 0;
var onKeyDown = function(event) {
if (event.keyCode == 67) { // when 'c' is pressed
object.traverse(function(child) {
if (child instanceof THREE.Mesh) {
var colors = [cleana, cleanb];
if (child.material.name == "meta") {
if (index == colors.length) index = 0;
child.material = colors[index++];
child.material.needsUpdate = true;
child.geometry.buffersNeedUpdate = true;
child.geometry.uvsNeedUpdate = true;
}
}
}
};
document.addEventListener('keyup', onKeyDown, true);
});
Please let me know if there is another way to do this.
If you want to exchange the whole material you need to do:
child.material = cleana;
or
child.material = cleanb;
and then you most likely have to do:
child.material.needsUpdate = true;
Read more on how to update material in this How to update things reference page in the chapter Materials
UPDATE
So if you want to set using an array:
var materials = [cleana, cleanb];
child.material = materials[0]; // cleana
or
child.material = materials[1]; // cleanb
and then also most likely:
child.material.needsUpdate = true;
It works totally fine with an array of materials. You don't even need to set material.needsUpdate = true. A demonstration here in this fiddle.
var leftf;
var rightf;
$(document).keyup(function() {
clearInterval(leftf);
clearInterval(rightf);
});
$(document).keydown(function (e) {
if (e.which == 37) {
// Left Arrow Pushed
leftf=setInterval(function(){
meshes[0].rotation.y=Math.PI/4;
if(meshes[0].position.x>-3.5)meshes[0].position.x-=0.1;
console.log(meshes[0].position.x);
},1000/engine.getFps());
} else if (e.which == 39) {
// Right Arrow Pushed
meshes[0].rotation.y=3*Math.PI/4;
//meshes[0].translate(BABYLON.Axis.X, Math.sin(v), BABYLON.Space.WORLD);
rightf=setInterval(function(){
meshes[0].position.x+=0.1;
},1000/engine.getFps());
}
});
Can you please tell me why this is not working in the browser although it is in my opinion the right way of moving the mesh on the screen without being torn (torn animation)?
It starts moving the mesh correctly but after a while the mesh is flying around without the logic. Is setting and clearing the Interval such a problem for the browsers?
Thank you.
Now it is running, perhaps I have a solution:
<!DOCTYPE html>
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Babylon.js sample code keyboard arrows</title>
<!-- Babylon.js -->
<script src="index_subory/hand.js"></script>
<script src="index_subory/cannon.js"></script>
<script src="index_subory/oimo.js"></script>
<script src="index_subory/babylon.2.0.debug.js"></script>
<script src="index_subory/jquery.min.js"></script>
<style>
html, body {
overflow: hidden;
width: 100%;
height: 100%;
margin: 0;
padding: 0;
}
#renderCanvas {
width: 100%;
height: 100%;
touch-action: none;
}
</style>
</head>
<body>
<div id="idecko" style="background-color:grey;color:white;font-weight:bold;margin-left:auto;margin-right:auto;text-align:center;">text </div>
<canvas height="782" width="1440" id="renderCanvas"></canvas>
<script>
var canvass = $('#renderCanvas');
// check to see if we can do webgl
// ALERT FOR JQUERY PEEPS: canvas is a jquery obj - access the dom obj at canvas[0]
var dcanvas = canvass[0];
expmt = false;
if ("WebGLRenderingContext" in window) {
//alert("browser at least knows what webgl is.");
}
// some browsers don't have a .getContext for canvas...
try {
gl = dcanvas.getContext("webgl");
}catch (x){
gl = null;
}
if (gl == null) {
try {
gl = dcanvas.getContext("experimental-webgl");
}catch (x){
gl = null;
}
if (gl == null) {
//console.log('but can\'t speak it');
}else {
expmt = true; //alert('webgl experimentally.');
}
} else {
//alert('webgl natively');
}
if (gl || expmt) {
//alert("loading webgl content.");
} else {
alert("CHYBA: Váš prehliadač nepodporuje WebGL, ľutujeme. (ERROR: Your browser does not support WebGL, sorry.)");
canvas.remove();
}
if (BABYLON.Engine.isSupported()) {
var canvas = document.getElementById("renderCanvas");
var engine = new BABYLON.Engine(canvas, true);
var scene = new BABYLON.Scene(engine);
// Skybox
var skybox = BABYLON.Mesh.CreateBox("skyBox", 800.0, scene);
var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", scene);
skyboxMaterial.backFaceCulling = false;
skyboxMaterial.reflectionTexture = new BABYLON.CubeTexture("index_subory/skybox/cubemap", scene);
skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
skyboxMaterial.diffuseColor = new BABYLON.Color3(0, 0, 0);
skyboxMaterial.specularColor = new BABYLON.Color3(0, 0, 0);
skybox.material = skyboxMaterial;
//var sphere = BABYLON.Mesh.CreateSphere("sphere", 1.0, 1.0, scene);
var createScene = function () {
// setup environment
var light0 = new BABYLON.PointLight("Omni", new BABYLON.Vector3(0, 10,80), scene);
var camera = new BABYLON.FreeCamera("FreeCamera", new BABYLON.Vector3(0, 0, -5), scene);
var light2 = new BABYLON.PointLight("Omni", new BABYLON.Vector3(10, 10, -80), scene);
var turnLeft = false; var turnRight = false;
var accelerate = false; var breaking = false;
BABYLON.SceneLoader.ImportMesh("Cube.001", "index_subory/", "jet2b.babylon", scene,function(meshes){
meshes[0].position.x = Math.round((Math.random() * 1) + 0);
meshes[0].position.y = Math.round((Math.random() * 1) + 0);
var speed = 0;
scene.registerBeforeRender(function() {
if (scene.isReady()) {
camera.target = sphere.position;
speed=0.02;
if (turnRight) {
meshes[0].rotation.y=3*Math.PI/4;
meshes[0].position.x += speed;
}
if (turnLeft) {
meshes[0].rotation.y=Math.PI/4;
meshes[0].position.x -= speed;
}
if (breaking) {
meshes[0].rotation.y=Math.PI/2;
meshes[0].position.y -= speed;
}
if (accelerate) {
meshes[0].rotation.y=Math.PI/2;
meshes[0].position.y += speed;
}
}
});
var sphere = BABYLON.Mesh.CreateSphere("sphere", 0.5, 0.5, scene);
var simpleMaterial = new BABYLON.StandardMaterial("texture2", scene);
simpleMaterial.diffuseColor = new BABYLON.Color3(0, 1, 0);//Green
sphere.material=simpleMaterial;
sphere.position.x = Math.floor((Math.random() * 2) );
sphere.position.y = Math.floor((Math.random() * 2) );
sphere.position.z=3;
var myVar2;
function myFunction2() {
myVar = setInterval(function(){
//sphere.translate(BABYLON.Axis.Z, -0.1, BABYLON.Space.WORLD);
sphere.position.z-=0.1;
var delta=0.2;
if(Math.abs(Math.round(meshes[0].position.x-sphere.position.x))<=delta&&Math.abs(Math.round(meshes[0].position.y-sphere.position.y))<=delta&&Math.abs(Math.round(meshes[0].position.z-sphere.position.z))<=delta){
$('#idecko').html('<span style=\'background-color:yellow;color:red;\'>BANG! Červeného trpaslíka trafila zelená planéta! (Red dwarf shot by green planet!)</span>');
//$('#idecko').append("<embed src='index_subory/explosion.mp3' hidden=true autostart=true loop=false>");
if(navigator.userAgent.indexOf("Trident")==-1)var audio = new Audio('index_subory/explosion.mp3');
if(navigator.userAgent.indexOf("Trident")!=-1)var audio = new Audio('index_subory/explosion.wav');
audio.loop = false;
audio.play();
simpleMaterial.diffuseColor = new BABYLON.Color3(0, 0, 1);//Green
sphere.material=simpleMaterial;
}else{
$('#idecko').html('<span style=\'background-color:grey;color:white;\'>Unikaj červený trpaslík (šípky na klávesnici)! (Run away red dwarf (keyboard arrows)!)</span>');
}
if(sphere.position.z<-5){
sphere.position.x = Math.floor((Math.random() * 2) );
sphere.position.y = Math.floor((Math.random() * 2) );
sphere.position.z=3;
simpleMaterial.diffuseColor = new BABYLON.Color3(0, 1, 0);//Green
sphere.material=simpleMaterial;
}
}, 50);
}
function myStopFunction2() {
clearTimeout(myVar2);
}
myFunction2();
$(document).keyup(function (evt) {
if (evt.keyCode == 37 || evt.keyCode == 39) {
turnLeft = false;
turnRight = false;
}
if (evt.keyCode == 38 || evt.keyCode == 40) {
accelerate = false;
breaking = false;
}
});
$(document).keydown(function (evt) {
if (!scene)
return;
//console.log(evt.keyCode);
if (evt.keyCode == 32) {
}
//Key LEFT
if (evt.keyCode == 37) {
turnLeft = true;
turnRight = false;
}
//Key RIGHT
if (evt.keyCode == 39) {
turnLeft = false;
turnRight = true;
}
//Key UP
if (evt.keyCode == 38) {
accelerate = true;
breaking = false;
}
//Key BACK
if (evt.keyCode == 40) {
breaking = true;
accelerate = false;
}
});
});
return scene;
}
var scene = createScene();
var assetsManager = new BABYLON.AssetsManager(scene);
//var meshTask = assetsManager.addMeshTask("jet2 task", "", "./index_subory/", "jet2.babylon");
var textTask0 = assetsManager.addTextFileTask("text task0", "./index_subory/jet2b.babylon");
var textTask1 = assetsManager.addTextFileTask("text task1", "./index_subory/hand.js");
var textTask2 = assetsManager.addTextFileTask("text task2", "./index_subory/cannon.js");
var textTask3 = assetsManager.addTextFileTask("text task3", "./index_subory/oimo.js");
var textTask4 = assetsManager.addTextFileTask("text task4", "./index_subory/babylon.2.0.debug.js");
var textTask5 = assetsManager.addTextFileTask("text task5", "./index_subory/jquery.min.js");
var binaryTask1 = assetsManager.addBinaryFileTask("binary task 1", "./index_subory/explosion.mp3");
var binaryTask2 = assetsManager.addBinaryFileTask("binary task 2", "./index_subory/explosion.wav");
var binaryTask3 = assetsManager.addBinaryFileTask("binary task 3", "./index_subory/skybox/cubemap_nx.jpg");
var binaryTask4 = assetsManager.addBinaryFileTask("binary task 4", "./index_subory/skybox/cubemap_ny.jpg");
var binaryTask5 = assetsManager.addBinaryFileTask("binary task 5", "./index_subory/skybox/cubemap_nz.jpg");
var binaryTask6 = assetsManager.addBinaryFileTask("binary task 6", "./index_subory/skybox/cubemap_px.jpg");
var binaryTask7 = assetsManager.addBinaryFileTask("binary task 7", "./index_subory/skybox/cubemap_py.jpg");
var binaryTask8 = assetsManager.addBinaryFileTask("binary task 8", "./index_subory/skybox/cubemap_pz.jpg");
//engine.displayLoadingUI();
engine.loadingUIText = "Loading... (Načítavanie...)";
assetsManager.onTaskSuccess = function (task) {
// Do something with task.data.
//engine.hideLoadingUI();
};
assetsManager.onTaskError = function (task) {
// Do something with task.data.
alert('Error with loading by assetsManager...');
};
assetsManager.onFinish = function (task) {
//engine.hideLoadingUI();
engine.setSize($(window).width(), $(window).height());
engine.runRenderLoop(function () {
scene.render();
});
};
assetsManager.load();
// Resize
window.addEventListener("resize", function () {
engine.resize();
});
}else{
alert("Chyba: Nemôžem spustiť WebGL. (Error: Can't run WebGL.)");
}
</script>
</body></html>