JavaScript - Question About Array And Object Syntax
The following code snippet:
(this.inputArray is already defined and initialized prior to this code sequence) if(this.inputArray.length >= 0) { this.inputArray[this.inputArray.length] = new Object(); this.inputArray[this.inputArray.length].type = 'pcDisp'; this.inputArray[this.inputArray.length].data = a; } the first line in the code block should create a new array item and initialize it with the various assigments in the next lines. But Firefox complains "this.inputArray[this.inputArray.length] is not defined". This is very disconcerting because the code has to create array items with different data based on conditionals. So I must be able to automatically create new items as necessary. I thought that javascript had 'late binding', but maybe that doesn't apply here. So, does anyone have a clue for me? Similar TutorialsI'm writing a program that involves a network of interconnected nodes (or simply objects in my example below). It depends on being able to access properties of an object's linked objects (a bit oddly worded, sorry)... Problem is I'm not sure how to properly access those properties... see below please. <script> //This is an example of a problem im having in my own code... //I want to access the name of the object within the links array wintin the object... var objA = {name: "Object A", links: [objB, objC]}; var objB = {name: "Object B", links: [objC, objD, objE]}; var objC = {name: "Object C", links: [objB]}; var objD = {name: "Object D", links: [objE]}; var objE = {name: "Object E", links: [objD]}; //ex: I want to access the name of Object A's first link... console.log(objA.links[0].name); </script> I'm hoping to get "Object B"... But instead I get: TypeError: Result of expression 'objA.links[0]' [undefined] is not an object. Is there another way around this? Any thoughts are appreciated. I have an alert I'm using over in Salesforce to remind sales reps to use a special terms document when quoting. Problem is, the alert is going off for ALL accounts, not just "Account1" and "Account2". Is this line incorrect in syntax or something? if ((isstatus == "Proposal/Price Quote") && (acct == "Account1", "Account2")) Thanks all. This forum has been very helpful for me in the past so this was my first stop! Jeremy Code: <html> <head> <script type="text/javascript" language="javascript" src="/js/functions.js"></script> <script type="text/javascript" src="/soap/ajax/10.0/connection.js"></script> <script type="text/javascript"> function throwalert() { var isstatus = "{!Opportunity.StageName}"; var acct = "{!Opportunity.Account}" var msgg = "Please remember to use a special terms and conditions quote template when quoting this opportunity."; if ((isstatus == "Proposal/Price Quote") && (acct == "Account1", "Account2")) { alert(msgg); } else { window.parent.location.replace = "{URLFOR($Action.Opportunity.View, Opportunity.Id,null,true)};" } } </script> </head> <body onload="throwalert()";> </body> </html> When using anonymous wrappers (I guess they are called like that), what does "()" part do at the end of the stack? An example: Code: ( function() {} ) () //Here! What does it do and how can we use it? I am studying the javascript. I got following codes from json2.js but do not understand syntax of them. if (!this.JSON) { this.JSON = {}; } (function () { ... }()); For 2nd part, why there is () outsider function? and why these is () after function? Thanks a lot. I was going through an article on JavaScript objects on "http://www.howtocreate.co.uk/tutorials/javascript/javascriptobject" and there I read Quote: Intrinsic objects - variable types with constructors. * Array * Boolean * Date * Function * Image * Number * Object * Option * Regular Expression * String does it mean that, whenever I want to use any of these objects, I have to create it using new and only then I can use its properties or methods ? 1) There are other objects like document, history, location, navigator, parent and screen. If objects which need to be created using constructor are called intrinsic objects , then what are other objects which can be used without constructor are called as ? Array, Boolean, Image, Date etc all start with capital letter. While document, history, navigator etc start with lower case letter. Why is that ? Is there any difference between objects that start with upper case and those start with lower case ? Are they known by different names ? Thanks if location is a property of window object that returns a string and im appending .indexOf() to location why is it not working?
My site will change color schemes when a user presses the button in the top left. I want to add a third theme though. I can't figure it out though. My html as relevent Code: <!--EXTERNAL FILES--> <link rel="stylesheet" type="text/css" href="main.css" /> <!--[if IE]><link rel="stylesheet" type="text/css" href="mainIE.css" /><![endif]--> <link id="altstyle" rel="stylesheet" type="text/css" href="main.css" /> <script type="text/javascript" src="main.js"></script> <!--STOP EXTERNAL FILES--> <title>Votillity.com</title> <!--CSS INTERNAL--> <!--CSS INTERNAL--> <!--JAVASCRIPT INTERNAL--> <!--JAVASCRIPT INTERNAL--> </head> <body onload="startTime()"> <img class="Zindexsty1" style="position: fixed; top: 0px; left: 0px;" src="http://votillity.com/VotillityLogo1.png" alt="VOTILLITY" /> <img class="Zindexsty2" style="position: fixed; top: 0px; left: 0px;" src="http://votillity.com/VotillityLogo2.png" alt="VOTILLITY" /> <button id="altstyact" class="button" style="position: fixed; top: 0px; left: 170px; width: 60px;">Theme</button> Javascript Code: //ALTERNATE STYLES function changeStyle() { var obj1=document.getElementById('altstyact'); var obj2=document.getElementById('altstyle') test=true; obj1.onclick=function() { test==true? (obj2.href='main2.css',obj1.firstChild.nodeValue='Classic',test=false): (obj2.href='main.css',obj1.firstChild.nodeValue='Ice',test=true) } } if(window.addEventListener) { window.addEventListener('load',changeStyle,false); } else { if(window.attachEvent) { window.attachEvent('onload',changeStyle); } } //STOP ALTERNATE STYLES I don't think you need the css's. If, however, I'm wrong just let me know. Keep in mind that the javascript is external. Here's my site if you need a better look Votillity Thank you Hello, I'm trying to write my class with member properties and functions like below. What I want to learn is that is there any problem to use prototype object in the class that we want to use with it? I asked because I generally see that prototype object definition and member functions and properties created outside of the class unlike my class that I wrote like below. Is there any problem writing my class like below? Thanks. Code: function Point() { Point.prototype.x = this._x; Point.prototype.y = this._y; function _setX(x) { this.x = x; } Point.prototype.setX = _setX; function _setY(y) { this.y = y; } Point.prototype.setY = _setY; function _show() { alert(this.x + this.y); } Point.prototype.Show = _show; } function callMyClass() { var p = new Point(); p.setX(3); p.setY(5); p.Show(); } My question is commented in the script: Code: function Love(){ var req = { ring : 'gold', money : 'a lot', commitment : 'long-term' } this.loveReqs = function(){ return req; } } var you = new Love(); var details = you.loveReqs(); details.ring = "silver"; console.log(details.ring); var me = new Love(); var details = me.loveReqs(); console.log(details.ring); // why does this return gold and not silver if req is passed by reference and we already changed its value above and so it's pointing to the same memory position? This is a constructor function. PROC will be an instantiation of another constructor. It will have a copy of GLBS. function _CALC_ELEMENTS(ELEM, GLBS, PROC) // PROC will also have a copy of GLBS. So, techincally, how could I access the copy of GLBS in PROC, via instance of _CALC_ELEMENTS. If I can do this, I do not need to include it directly. (GLBS is yet another object instantiated via constructor) I am just concerned that there are two copies when only one is necessary. Thanks for thoughts on this JK Hi, I have an array but I'm not exactly sure how to finish the build using an if statement. I have 6 elements and need the build to load a different top image for each array that loads that matches the specific element. Here is what I have but it only shows the first top image no matter what: PHP Code: <LINK REL=StyleSheet HREF="scrolling_popup/scrolling_popup.css" TYPE="text/css"> <script type="text/javascript" language="javascript" src="scrolling_popup/scrolling_popup.js"></script> <script type="text/javascript" > var array = new Array(); array[0]='<a href="http://www.amateurmatch.com/in/?ainfo=MjI5MjR8Nnw3NDc=&atcc=0&_t=search3&id=489257" rel="nofollow" target="_blank"><img src="http://www.oohya.net/geoip/p/1.jpg" border="0" alt=""></a>'; array[1]='<a href="http://www.amateurmatch.com/in/?ainfo=MjI5MjR8Nnw3NDc=&atcc=0&_t=search3&id=489257" rel="nofollow" target="_blank"><img src="http://www.oohya.net/geoip/p/2.jpg" border="0" alt=""></a>'; array[2]='<a href="http://www.amateurmatch.com/in/?ainfo=MjI5MjR8Nnw3NDc=&atcc=0&_t=search3&id=489257" rel="nofollow" target="_blank"><img src="http://www.oohya.net/geoip/p/3.jpg" border="0" alt=""></a>'; array[3]='<a href="http://www.amateurmatch.com/in/?ainfo=MjI5MjR8Nnw3NDc=&atcc=0&_t=search3&id=489257" rel="nofollow" target="_blank"><img src="http://www.oohya.net/geoip/p/4.jpg" border="0" alt=""></a>'; array[4]='<a href="http://www.amateurmatch.com/in/?ainfo=MjI5MjR8Nnw3NDc=&atcc=0&_t=search3&id=489257" rel="nofollow" target="_blank"><img src="http://www.oohya.net/geoip/p/5.jpg" border="0" alt=""></a>'; array[5]='<a href="http://www.amateurmatch.com/in/?ainfo=MjI5MjR8Nnw3NDc=&atcc=0&_t=search3&id=489257" rel="nofollow" target="_blank"><img src="http://www.oohya.net/geoip/p/6.jpg" border="0" alt=""></a>'; var num=Math.floor(Math.random()*(array.length) ); var html_code = array[num]; if (array[0]) { buildPopup_HtmlCode(390, 329, '<img src="http://www.oohya.net/geoip/images/imtop1.png">', html_code); } else if (array[1]) { buildPopup_HtmlCode(390, 329, '<img src="http://www.oohya.net/geoip/images/imtop2.png">', html_code); } else if (array[2]) { buildPopup_HtmlCode(390, 329, '<img src="http://www.oohya.net/geoip/images/imtop3.png">', html_code); } else if (array[3]) { buildPopup_HtmlCode(390, 329, '<img src="http://www.oohya.net/geoip/images/imtop4.png">', html_code); } else if (array[4]) { buildPopup_HtmlCode(390, 329, '<img src="http://www.oohya.net/geoip/images/imtop5.png">', html_code); } else { buildPopup_HtmlCode(390, 329, '<img src="http://www.oohya.net/geoip/images/imtop6.png">', html_code); } </script> Any ideas? Hi all, I am trying to build a config object for a program using a loop. Here's what I've done so far (note: "bbtags" is an array built like this): var bbtags = new Array((b),(/b),(i),(/i),(u),(/u),etc......); (note I used parentheses in place of brackets soas not to confuse the board.) Code: var arr = []; var len = bbtags.length; var tag = ''; var obj = ''; for (var i = 0; i < len; i+=2) { tag = bbtags[i].replace(/\[(.*?)\]/gi,'$1'); // strip off the brackets name = String('mce_' + tag); // generate a name obj = { name : { 'block' : name } } arr.push(obj); } The RESULT that I am after would look like this: Code: mce_b : { 'block' : 'mce_b' }, mce_i : { 'block' : 'mce_i' }, mce_u : { 'block' : 'mce_u' }, etc....... Notice the items I marked in red. Instead of these items having the VALUE of the variable "name", they instead have value of "name". That is, every part in red is "name". Any ideas how to make this work right (or an idea how to do it BETTER)? Thanks! -- Roger I am trying to parse a string so I can put points into google maps api. Here is the string i am using: Code: CountySide Town 66202 KS COUNTRYSIDE,39.025376,-94.766998|Shawnee City 66203 KS SHAWNEE,39.019802,-94.808303 Here is the javascript I am using: Code: var a = new Array(); function parseAddress(addressString) { alert(addressString); var prompt = addressString.split("|"); for (var i = 0; i < prompt.length; i++) { var details = prompt[i].split(","); var t = new Object(); t.name = details[0] t.lat = details[1] t.lng = details[2] a[i] = t; } } I have found if I do something like this: Code: var t = new Object(); t.name = "Shawnee" t.lat = 39.019802 t.lng = -94.708303 a[0] = t; var t = new Object(); t.name = "Overland Park" t.lat = 38.992488, t.lng = -94.674769 a[1] = t; It will work, can someone tell me why my loop doesnt work? Hi, I am trying to create an array to pass to JQuery, but after several hours of trying, am falling over. I am trying to use Ajax to populate the javascript FullCalendar. I am trying to pass an arry to the following property: This works: $('#calendar').fullCalendar({ events: [{"id":1112,"title":"Event1","start":"2009-10-10"},{"id":222,"title":"Event2","start":"2009-10-20","end":"2009-10-22"}] }; something like: $('#calendar').fullCalendar({ events: MyJSArray() }; I will be using AJAX to populate MyJSArray(). I have tried the likes of: MyJSArray = new array("id"=>112,"title"=>"Event1", etc); But no joy I don't know how to get a javascript array into that format. I have my database values, but I need to put them into a format that the "Event" will accept. I have used PHP and arrays fine, but coming to grips with JS arrays,etc are a bit finiky at the moment. I am a little stuck, any help or points in the right direction will be much appreciated. Thanks Blueevo. function get_price() { var the_price=1000; if (this.speed=="500MGz") the_price+=200; else the_price+=100; if (this.hdspace=="15GB") the_price+=50; else the_price+=25; if (this.ram=="128MB") the_price+=150; else the_price+=75; return the_price; } function computer(speed,hdspace,ram) { this.speed=speed; this.hdspace=hdspace; this.ram=ram; this.price=get_price; } var work_computer=new computer("2GHz","80GB","1GB"); var home_computer=new computer("1.5GHz","40GB","512MB"); var laptop_computer=new computer("1GHz","20GB","256MB"); var work_computer_price=work_computer.price(); var home_computer_price=home_computer.price(); var laptop_computer=laptop_computer.price(); ___________________________________________________ In the above code, the line I'm having trouble with is marked red. Why is it that when I call the method using ... this.price = get_price; It works fine. But if I assign the object this.price with like this... this.price = get_price(); I get an error? Isn't get_price() a function? So shouldn't the parenthesis be included when the method is called? Why are we suppose to leave out the parenthesis?! I'm confused. Thanks! I have an array of objects that I would like to sort through and "join" objects that are the same. And if they are the same, I need to sum up the number value given for those two items. So I guess Im sorting through and maybe even recreating this array to get rid of duplicates while I tally quantities. Please see the screenshot of my array of objects to help understand better. The highlighted 'sPSPN' would indicate that it is a duplicate item and its 'fUnits' need to be totalled. in the end I would have a total of 3 objects, because 'sPSPN'= BT-221-44 would now be only one object with 'fUnits' = 35. Thanks! Hi all, I'm wondering if what I'm trying to do here is even possible but I'd appreciate your thoughts on it. Code: <script type="text/javascript"> function test() { var arrays = { one: ['1', '2', '3'], two: ['a', 'b', 'c'] } var foo = 'one'; alert(arrays.(foo)); } test(); </script> I've tried numerous variations of the alert line with evals, brackets and jQuery syntax but always seem to get the error: Code: XML filter is applied to non-XML value ({one:["1", "2", "3"], two:["a", "b", "c"]}) Which makes me think I'm either attempting something stupid or only missing my target slightly. The code will be running within a jQuery project up if that helps in any way. Hello, I've made a JS code that declare events based on year, month and days. Each date represents an event. The code works well but I'd like to improve the declaration when several days with the same description are following to reduce declaration lines. Here's the actual working code: var events = [ >> {year: '2011', month: '11',day: '1',description: "test description",url: '',newpage: false,mark_as_event: false}, >> {year: '2011', month: '11',day: '2',description: "test description",url: '',newpage: false,mark_as_event: false}, >> {year: '2011', month: '11',day: '3',description: "test description",url: '',newpage: false,mark_as_event: false}, >> {year: '2011', month: '11',day: '4',description: "test description",url: '',newpage: false,mark_as_event: false}, //I would like replace the 4 lines here above by something like this: >>>>> {year: '2011', month: '11',(day: '1','2','3'),description: "test description",url: '',newpage: false,mark_as_event: false}, {year: '2011', month: '11',day: '11',description: "11 november",url: '',newpage: false,mark_as_event: false}, {year: '2012', month: '4',day: '30',description: "easter",url: '',newpage: false,mark_as_event: false}, {year: '2012', month: '5',day: '1',description: "1 mai",url: '',newpage: false,mark_as_event: false}, {year: '', month: '',day: '',description: "",url: '',newpage: true,mark_as_event: true} ]; var temp_date=new Array(); //init current month data var temp_url=new Array(); var temp_newpage=new Array(); var temp_mark_as_event=new Array(); for (var i = 0; i < events.length; i++) { //Current month data are used here if (events[i].year==cal_year && events[i].month==(cal_month + 1)){ temp_date[events[i].day]=events[i].description; temp_url[events[i].day]=events[i].url; temp_newpage[events[i].day]=events[i].newpage; temp_mark_as_event[events[i].day]=events[i].mark_as_event; } } Is it possible and how ? Thank you very much Gino Hi I need help with spawning in my game. I have this code: Code: function spawnEnemy() { var shapes = [LeftBlock, RightBlock, middleRightBlock, middleLeftBlock, middleBlock]; var shape = shapes[Math.floor(Math.random() * shapes.length)]; var RandomBlock = new THREE.Object3D(); RandomBlock.add(shape); blocks.push(RandomBlock); for (var i = 0; i < blocks.length; i++) { RandomBlock = blocks[i]; scene.add(RandomBlock); hit = false; } } function startSpawningEnemies() { repeater = setInterval(function() { spawnEnemy(); newBlock = false; }, 1000); } Basically it chooses a random object in the array 'shapes' and it adds the shape to the scene every second. But the problem is that when I have, for example a 'Leftblock' on screen and it randomly gets called again, Leftblock will get reset to the starting position, so basically I cant have 2 of the same type of block on screen at once. So I want want every block in the array to be an entirely new instance of a block, rather than the same. Here is a code pen so you can see what is happening My Codepen Thanks in advance Reply With Quote 01-31-2015, 12:06 PM #2 Lesshardtofind View Profile View Forum Posts Visit Homepage New Coder Join Date Sep 2013 Location Houston Posts 20 Thanks 0 Thanked 4 Times in 4 Posts Hey I apologize in advance this will probably be a long post, but to get to the root of your problem it takes a bit of explaining to show how I fixed it. If you don't want to read about all the changes and why I did them if you scroll to the bottom of this post the last code snippet is the new working code. Firstly I'd like to make a few comments. 1. Try to avoid using so many globals that is what is confusing the whole thing. 2. Even though JavaScript isn't a classical language. Using some OOP approaches can simplify your code quite a bit. Now to what your actual problem was. You only had one instance of meshes for each type of block/paddle or whatever you call it. Even though you created new 3d objects you still were just passing it the values of the current existing Meshes. In order to get around this I simplified your code a lot. I removed around 200 lines of code and created a few objects to make things easier. I don't know that I can explain every single thing I did, but creating objects is very useful for instance instead of making a ton of variables for each box you can make an Object called Box and then create a new instance of it. Since your Box also needs a mesh you can create that inside of the box as well. Code: function Box(w, h, d, q, m){ var CoreInfo = { width: w, height: h, depth: d, quality: q, material: m }; var Mesh = GetNewMesh(CoreInfo); this.setMeshY = function(y){ Mesh.position.y = y; } this.setMeshX = function(x){ Mesh.position.x = x; } this.getCoreInfo = function(key){ return CoreInfo[key]; } this.setCoreInfo = function(key, val){ CoreInfo[key] = val; } this.getAllInfo = function(){ return CoreInfo; } this.getMesh = function(){ return Mesh; } this.setShadows = function(r, c){ Mesh.receiveShadow = r; Mesh.castShadow = c; } } // you will notice that it calls this to get a MESH instead of using 5+ serperate calls you can now wrap it into a function that takes an assoc array. function GetNewMesh(info){ var Q = info["qaulity"]; return new THREE.Mesh( new THREE.BoxGeometry( info["width"], info["height"], info["depth"], Q, Q, Q), info["material"]); } With this object you can create new instances of boxes just by passing all the variables it needs and save it into a new object. example use: Code: var BlockMat = new THREE.MeshLambertMaterial({color: 0x3c00ff}); var Abox = new Box(10, 160, 10, 1, BlockMat); As you can see the Box requires 5 arguments to construct. They are width, height, depth, quality, and material; You will also notice there are functions inside of the Box to call functionality they are setMeshY(y): This sets the Y position of the mesh as the y value passed to it; setMeshX(x): This sets the X position of the mesh as the x value passed to it; getCoreInfo(key): This gets some CoreInfo based on a string or "key" that you pass it. EX use Box.getCoreInfo("width"); setCoreInfo(key, value): This sets some CoreInfo based on a string or "key" that you pass it. EX use Box.setCoreInfo("width", 100); getAllInfo(): Returns ALL CoreInfo in an assoc array that is accessed by a "key." EX use var AllInfo = Box.getAllInfo(); AllInfo["width"]; getMesh: Returns The mesh object setShadows: Allows you to set shadows by passing true or false for the receive and cast arguments. Now some of your enemy boxes needed two boxes so I further created a object called Double Box; These are very much the same as a box. Just all methods need to be passed an index as well. These are identical to your original objects as Paddle1 is now at index 0, and Paddle2 is at index1 for each respective object. With those objects created we can Delete a TON of your global variables and clean some stuff up. As a matter of fact the more I looked at it you didn't even NEED globals for your set enemy paddle types at all. I was able to wrap them all up into a function that will return an object like you wanted by being passed a string. Code: function GetBlock(type){ if(type == "m"){ var temp = new DoubleBox(10, 75, 10, 1, BlockMat, 10, 75, 10, 1, BlockMat); var obj = new THREE.Object3D(); obj.add(temp.getMesh(0)); obj.add(temp.getMesh(1)) temp.setMeshX(0, fieldWidth/2); temp.setMeshY(0, -60); temp.setMeshX(1, fieldWidth/2); temp.setMeshY(1, 60); return obj; } else if(type == "mr"){ var temp = new DoubleBox(10, 30, 10, 1,BlockMat, 10, 110, 10, 1,BlockMat); var obj = new THREE.Object3D(); obj.add(temp.getMesh(0)); obj.add(temp.getMesh(1)); temp.setMeshX(0, fieldWidth/2); temp.setMeshY(0, -80); temp.setMeshX(1, fieldWidth/2); temp.setMeshY(1, 40); return obj; } else if(type == "ml"){ var temp = new DoubleBox(10, 30, 10, 1, BlockMat, 10, 110, 10, 1, BlockMat); var obj = new THREE.Object3D(); obj.add(temp.getMesh(0)); obj.add(temp.getMesh(1)); temp.setMeshX(0, fieldWidth/2); temp.setMeshY(0, 80); temp.setMeshX(1, fieldWidth/2); temp.setMeshY(1, -40); return obj; } else if(type == "l"){ var temp = new Box(10, 160, 10, 1, BlockMat); var obj = new THREE.Object3D(); obj.add(temp.getMesh()); temp.setMeshX(fieldWidth/2); temp.setMeshY(20); return obj; } else if(type == "r"){ var temp = new Box(10, 160, 10, 1, BlockMat); var obj = new THREE.Object3D(); obj.add(temp.getMesh()); temp.setMeshX(fieldWidth/2); temp.setMeshY(-20); return obj; } } While this could be cleaned up and do some extra error checking it now does EXACTLY what you need it to. You can call this function and pass it a string for each type of block you want. It will return a NEW instance of that type of block without sharing meshes as you had previously programmed it to. now you can call this function in the spawn enemy function Code: function spawnEnemy() //total enemies starts at 0 and every-time you add to array { var shapes = ["l", "r", "mr", "ml", "m"]; // these are the strings that pass to the GetBlock(type) function as type var shape = shapes[Math.floor(Math.random() * shapes.length)]; blocks.push(new THREE.Object3D().add(GetBlock(shape))); // now you just pass the function to the THREE.Object3d().add() accepting shape as a parameter. for (var i = 0; i < blocks.length; i++) { RandomBlock = blocks[i]; scene.add(RandomBlock); hit = false; } } I know I made a lot of changes and there are still plenty more that could reduce your code even further, but when I finally got to a point where it was working the way you wanted to I figured I'd hand it back over to you. HERE is the final code that works if you want to copy paste it over to test it. Code: //scene object variables var renderer, scene, camera, pointLight, spotLight; var hit; var newBlock = false; //field variables var fieldWidth = 500, fieldHeight = 200; function GetNewMesh(info){ var Q = info["qaulity"]; return new THREE.Mesh( new THREE.BoxGeometry( info["width"], info["height"], info["depth"], Q, Q, Q), info["material"]); } function Box(w, h, d, q, m){ var CoreInfo = { width: w, height: h, depth: d, quality: q, material: m }; var Mesh = GetNewMesh(CoreInfo); this.setMeshY = function(y){ Mesh.position.y = y; } this.setMeshX = function(x){ Mesh.position.x = x; } this.getCoreInfo = function(key){ return CoreInfo[key]; } this.setCoreInfo = function(key, val){ CoreInfo[key] = val; } this.getAllInfo = function(){ return CoreInfo; } this.getMesh = function(){ return Mesh; } this.setShadows = function(r, c){ Mesh.receiveShadow = r; Mesh.castShadow = c; } } function DoubleBox(B1w, B1h, B1d, B1q, B1m, B2w, B2h, B2d, B2q, B2m) { var Boxes = []; Boxes[0] = new Box(B1w, B1h, B1d, B1q, B1m); Boxes[1] = new Box(B2w, B2h, B2d, B2q, B2m); this.setMeshY = function (index, y) { Boxes[index].setMeshY(y); } this.setMeshX = function (index, x) { Boxes[index].setMeshX(x); } this.getCoreInfo = function (index, key) { return Boxes[index].getCoreInfo(key); } this.setCoreInfo = function (index, key, val) { Boxes[index].setCoreInfo(key, val); } this.getAllInfo = function (index) { return Boxes[index].getAllInfo(); } this.getMesh = function (index) { return Boxes[index].getMesh(); } this.setShadows = function (index, r, c) { Boxes[index].setShadows(r, c); } } var BlockMat = new THREE.MeshLambertMaterial({color: 0x3c00ff}); var Player = new Box(10, 30, 10, 1, new THREE.MeshLambertMaterial({color: 0x4AA02C})); function GetBlock(type){ if(type == "m"){ var temp = new DoubleBox(10, 75, 10, 1, BlockMat, 10, 75, 10, 1, BlockMat); var obj = new THREE.Object3D(); obj.add(temp.getMesh(0)); obj.add(temp.getMesh(1)) temp.setMeshX(0, fieldWidth/2); temp.setMeshY(0, -60); temp.setMeshX(1, fieldWidth/2); temp.setMeshY(1, 60); return obj; } else if(type == "mr"){ var temp = new DoubleBox(10, 30, 10, 1,BlockMat, 10, 110, 10, 1,BlockMat); var obj = new THREE.Object3D(); obj.add(temp.getMesh(0)); obj.add(temp.getMesh(1)); temp.setMeshX(0, fieldWidth/2); temp.setMeshY(0, -80); temp.setMeshX(1, fieldWidth/2); temp.setMeshY(1, 40); return obj; } else if(type == "ml"){ var temp = new DoubleBox(10, 30, 10, 1, BlockMat, 10, 110, 10, 1, BlockMat); var obj = new THREE.Object3D(); obj.add(temp.getMesh(0)); obj.add(temp.getMesh(1)); temp.setMeshX(0, fieldWidth/2); temp.setMeshY(0, 80); temp.setMeshX(1, fieldWidth/2); temp.setMeshY(1, -40); return obj; } else if(type == "l"){ var temp = new Box(10, 160, 10, 1, BlockMat); var obj = new THREE.Object3D(); obj.add(temp.getMesh()); temp.setMeshX(fieldWidth/2); temp.setMeshY(20); return obj; } else if(type == "r"){ var temp = new Box(10, 160, 10, 1, BlockMat); var obj = new THREE.Object3D(); obj.add(temp.getMesh()); temp.setMeshX(fieldWidth/2); temp.setMeshY(-20); return obj; } } //ball variables var reftBlock, lightBlock, middleRightBlock, middleLeftBlock, middleBlock, RandomBlock; //game-related variables var score = 0; var repeater; var blocks = []; var collidableMeshList = []; function setup() { // update the board to reflect the max score for match win document.getElementById("winnerBoard").innerHTML = "Move in the gaps!"; // set up all the 3D objects in the scene createScene(); // and let's get cracking! draw(); } function createScene() { // set the scene size var WIDTH = 640, HEIGHT = 360; // set some camera attributes var VIEW_ANGLE = 50, ASPECT = WIDTH / HEIGHT, NEAR = 0.1, FAR = 10000; var c = document.getElementById("gameCanvas"); // create a WebGL renderer, camera // and a scene renderer = new THREE.WebGLRenderer({antialias:true}); renderer.setClearColorHex(0xffffff); camera = new THREE.PerspectiveCamera( VIEW_ANGLE, ASPECT, NEAR, FAR); scene = new THREE.Scene(); // add the camera to the scene scene.add(camera); // set a default position for the camera // not doing this somehow messes up shadow rendering //camera.position.z = 320; // start the renderer renderer.setSize(WIDTH, HEIGHT); // attach the render-supplied DOM element c.appendChild(renderer.domElement); // set up the playing surface plane var planeWidth = fieldWidth, planeHeight = fieldHeight, planeQuality = 10; // create the plane's material var planeMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff }); // create the table's material var tableMaterial = new THREE.MeshLambertMaterial( { color: 0x3c00ff }); // create the ground's material var groundMaterial = new THREE.MeshLambertMaterial( { color: 0xffffff }); // create the playing surface plane var plane = new THREE.Mesh( new THREE.PlaneGeometry( planeWidth * 1.25, // 95% of table width, since we want to show where the ball goes out-of-bounds planeHeight, planeQuality, planeQuality), planeMaterial); scene.add(plane); plane.receiveShadow = true; var table = new THREE.Mesh( new THREE.BoxGeometry( planeWidth * 1.15, // this creates the feel of a billiards table, with a lining planeHeight * 1.04, 100, // an arbitrary depth, the camera can't see much of it anyway planeQuality, planeQuality, 1), tableMaterial); table.position.z = -51; // we sink the table into the ground by 50 units. The extra 1 is so the plane can be seen scene.add(table); table.receiveShadow = true; scene.add(Player.getMesh()); startSpawningEnemies(); Player.setShadows(true, true) /*collidableMeshList.push(MiddleBlock.getMesh(0), MiddleBlock.getMesh(1), MiddleLeftBlock.getMesh(0), MiddleLeftBlock.getMesh(1), MiddleRightBlock.getMesh(0), MiddleRightBlock.getMesh(1), RightBlock.getMesh(), LeftBlock.getMesh());*/ // set paddles on each side of the table Player.setMeshX(-fieldWidth/2 + Player.getCoreInfo("width")); //collidableMeshList.push(RandomBlock); // finally we finish by adding a ground plane // to show off pretty shadows var ground = new THREE.Mesh( new THREE.BoxGeometry( 1000, 1000, 3, 1, 1, 1 ), groundMaterial); // set ground to arbitrary z position to best show off shadowing ground.position.z = -132; ground.receiveShadow = true; scene.add(ground); // // create a point light pointLight = new THREE.PointLight(0xffffff); // set its position pointLight.position.x = -1000; pointLight.position.y = 0; pointLight.position.z = 1000; pointLight.intensity = 2.9; pointLight.distance = 10000; // add to the scene scene.add(pointLight); // add a spot light // this is important for casting shadows spotLight = new THREE.SpotLight(0xffffff); spotLight.position.set(0, 0, 460); spotLight.intensity = 1.5; spotLight.castShadow = true; scene.add(spotLight); // MAGIC SHADOW CREATOR DELUXE EDITION with Lights PackTM DLC renderer.shadowMapEnabled = true; } function draw() { // draw THREE.JS scene renderer.render(scene, camera); // loop draw function call requestAnimationFrame(draw); cameraPhysics(); playerPaddleMovement(); enemyPaddleMovement(); collision(); //addScore(); } function addScore() { if (RandomBlock.position.x < Pad.getMesh().position.x*2 && newBlock == false) { console.log("pass"); newBlock = true; if (hit == false) { score++; } else { score-- } document.getElementById("scores").innerHTML = score; } } function enemyPaddleMovement() { if(score < 10) { for (var i = 0; i < blocks.length; i++) { blocks[i].position.x -= 3; } } if(score >= 10) { for (var i = 0; i < blocks.length; i++) { blocks[i].position.x -= 5; } } } function playerPaddleMovement() { if (Key.isDown(Key.D)) Player.setMeshY(80); else if (Key.isDown(Key.F)) Player.setMeshY(40); else if (Key.isDown(Key.H)) Player.setMeshY(0); else if (Key.isDown(Key.J)) Player.setMeshY(-40); else if (Key.isDown(Key.K)) Player.setMeshY(-80); } //Handles camera and lighting logic function cameraPhysics() { // move to behind the player's paddle camera.position.x = Player.getMesh().position.x - 100; camera.position.y += (Player.getMesh().position.y - camera.position.y) * 0.05; camera.position.z = Player.getMesh().position.z + 100 + 0.04 * (Player.getMesh().position.x); // rotate to face towards the opponent camera.rotation.y = -60 * Math.PI/180; camera.rotation.z = -90 * Math.PI/180; } //Handles paddle collision logic function collision() { var originPoint = Player.getMesh().position.clone(); for (var vertexIndex = 0; vertexIndex < Player.getMesh().geometry.vertices.length; vertexIndex++) { var ray = new THREE.Raycaster( originPoint, Player.getMesh().geometry.vertices[vertexIndex] ); var collisionResults = ray.intersectObjects( collidableMeshList ); if ( collisionResults.length > 0) { console.log("true"); hit = true; } } } function resetBall() { } //checks if either player or opponent has reached 7 points function matchScoreCheck() { } function spawnEnemy() //total enemies starts at 0 and every-time you add to array { var shapes = ["l", "r", "mr", "ml", "m"]; var shape = shapes[Math.floor(Math.random() * shapes.length)]; blocks.push(new THREE.Object3D().add(GetBlock(shape))); for (var i = 0; i < blocks.length; i++) { RandomBlock = blocks[i]; scene.add(RandomBlock); hit = false; } } function startSpawningEnemies() { repeater = setInterval(function() { spawnEnemy(); newBlock = false; }, 1000); //this calls spawnEnemy every spawnRate /////////spawn 'spawnAmount' enemies every 2 seconds } I also commented out your addScore() function because it references RandomBlock which is not defined in its scope and the error message was annoying for debugging. I also commented out the collision as you will need to think of a new method for doing that. Most likely just build a function that accepts an array and then just pass it your blocks array and let it loop through it. Overall cool game good luck to ya. Don't hesitate to reach out if you have any other questions. Reply With Quote Users who have thanked Lesshardtofind for this post: TeaAnyOne (01-31-2015) 01-31-2015, 02:31 PM #3 TeaAnyOne View Profile View Forum Posts New to the CF scene Join Date Jan 2015 Posts 4 Thanks 2 Thanked 0 Times in 0 Posts Wow! I didn't expect such a huge reply, it seems that my original code has changed a lot and I will have to give it a hard look through it to understand it. I will contact you if I have any questions, I have a lot of work ahead of me. Thanks a lot Reply With Quote 01-31-2015, 04:45 PM #4 TeaAnyOne View Profile View Forum Posts New to the CF scene Join Date Jan 2015 Posts 4 Thanks 2 Thanked 0 Times in 0 Posts I suppose I do have one more question. How do I get the position.x of the Randomblocks. I tried using a for loop like this: for (var i = 0; i < blocks.length; i++) { if (blocks[i].position.x === Player.getMesh().position.x*2 && newBlock === false) { console.log("pass"); newBlock = true; if (hit === false) { score++; } else { score--; } } document.getElementById("scores").innerHTML = score; } } it works but it seems kind of buggy as it stops counting to 10 when it changes speed. Is there another way to retrieve the position? Reply With Quote 01-31-2015, 07:43 PM #5 Lesshardtofind View Profile View Forum Posts Visit Homepage New Coder Join Date Sep 2013 Location Houston Posts 20 Thanks 0 Thanked 4 Times in 4 Posts That should work for getting the position since the Blocks are objects of type THREE.Object3d so any methods they have should work for you. You may be having problems because you never despawn enemies ultimately getting a huge number of 3d objects in your array blocks, or you may find your position requirement doesn't mathematically work with your speed up. Sometimes just using a few extra console.logs to track your numbers inside of functions that don't seem to be working can help you to get an idea of what values it is seeing for the numbers and when. It might make the problem super obvious. This more like shotgun debugging which is discouraged by many, but I found it to help a lot when I was first learning code. Ultimately you want to understand your logic in each function and how it can fail when you program it, and then use error checking to make sure no parameters get outside of your allowed variance. Reply With Quote Users who have thanked Lesshardtofind for this post: TeaAnyOne (01-31-2015) 01-31-2015, 08:27 PM #6 TeaAnyOne View Profile View Forum Posts New to the CF scene Join Date Jan 2015 Posts 4 Thanks 2 Thanked 0 Times in 0 Posts OK ill see if I can get it working. Thanks for all your help! It helped me a lot. Reply With Quote 01-31-2015, 08:31 PM #7 Old Pedant View Profile View Forum Posts Supreme Master coder! Join Date Feb 2009 Posts 28,310 Thanks 82 Thanked 4,754 Times in 4,716 Posts Originally Posted by Lesshardtofind Ultimately you want to understand your logic in each function and how it can fail when you program it, and then use error checking to make sure no parameters get outside of your allowed variance. Very well said! |