Posts tonen met het label javascript. Alle posts tonen
Posts tonen met het label javascript. Alle posts tonen

dinsdag 22 september 2015

LOI Gamedesign

Afgelopen vrijdag gaf ik GameDesign op HBO niveau voor de LOI.
Als onderdeel van deze cursus zou men gamemaker moeten leren.
Aangezien gameDesign voor alle leerlingen niet echt een hoofdvak was, maar meer een verplicht nummer, besloten we de game in Javascript te gaan maken,
Gamemaker is leuk als je wilt gameDesignen, zonder iets te willen programmeren. Maar als je een multimedia/frontend opleiding doet, dan is javascript toch wel een vereiste.

Javascript zat tot nog toe niet in de cursus, hetgeen een extra uitdaging vormde:
naast basic gamedevelopment, moest ik ze ook leren programmeren.
Gelukkig heb ik dat vaker bij de hand gehad, dus op naa JSFiddle.

http://jsfiddle.net/wn8rq0m0/
var a=4;
if(1==3)
{
 a=a+1;
}
console.log("------------");
console.log("de waarde van a ="+ a);

Mijn controle vraag aan de leerlingen om het niveau in te schatten is: "Wat gaat er gebeuren?" en
 "Wat wordt de waarde van a?"
Als je hier een antwoord op wil kunnen geven moet je twee basis-concepten van programmeren snappen. Variabelen en Expressies.

var a=4;
Een variabele (in dit geval a) wordt gedeclareerd.
Dit betekent, dat je javascript verteld, hoe de variabele heet en (eventueel) wat zijn initiele waarde is.
Je kunt het zien als het maken van een doosje (met een naam) waar je iets in kan stoppen, maar het hoeft niet direct.
In dit geval heet het doosje "a" en stoppen we er 4 in.

if(1==3)
Dit is een voorbeeld van een expressie. Je kunt dit zien aan de dubbele ==. We vragen de computer of wat tussen haakjes staat waar is, of niet waar.
Dus 1=3? geeft niet waar.
Het blok code daaronder.
{
 a=a+1;
}
wordt dus overgeslagen. (Bij een ware expressie bijvoorbeeld (1==1) was het WEL uitgevoerd).
Dit is de functie van if. Na if volgt een expressie en een blok code. Is de expressie waar, dan wordt het blok uitgevoerd, anders wordt het overgeslagen.
Op deze manier kan een programma reageren op veranderende omstandigheden. De expressie kan namelijk wat complexer zijn dan 1==3? Want dat is een domme vraag.

console.log("------------");
Dan wordt de javascript gevraagd, een boodschap af te drukken, deze vind je in je console. Dat is een speciale plek voor programmeurs. Afhankelijk van je browser vind je deze op andere plekken, vaak is f12 of ctrl-shift-i een goeie plek om te beginnen.

console.log("de waarde van a ="+ a);
Dit betekent, dat er een boodschap wordt afgedrukt. Het eerste deel van de boodschap is letterlijk en staat dus tussen aanhalingstekens. (In programmeren heet dit een string). Het tweede deel van de boodschap is de waarde van a. Deze worden samengevoegd door een plus-teken.

Het resultaat van het programma is dus:
----------------------
de waarde van a=4

Als je dit snapt, heb je al bijna alles wat nodig is om een spel te programmeren.
Even vooruitspringend naar wat je in 30 stappen gaat leren maken:


Ik zal het nog allemaal uitgebreid beschrijven als ik tijd heb, maar voor nu kun je het proces terughalen met:

dinsdag 8 juli 2014

Loopable Soft Noise

Generating Soft Noise on a Canvas

I'm making a space paralax game and I need a function for soft, loopable noise, to make space a little more interesting.
I've been looking at perlin-noise, but speed is an issue..

So I've been fiddling to generate this:
http://jsfiddle.net/LwDC9/1/

As you can see the texture is generated to be completely loopable at ANY format. (Perlin noise usually needs something like 2,4,8,16,32... etc)
If you want a 2048x2048 loopable texture, you'll have to wait a bit, but it'll get there. You can reduce the complexity of the rendering to optimize.

Also the texture is transparent. This is because I want to use it in a parallax.

So let's use that technique to create a huge (640x480) spaceview animation that you might know from games. (using a parallax)
http://jsfiddle.net/LwDC9/3/
Please try the fiddle, the image doesn't do justice to the animation.
I've put some text underneath the canvas, to show it's pretty transparant.
I'd like to see what the performance is on an iPad or something, but right now, I'm pretty happy with the performance in Chrome.

Now when a star dissappears it immeadeately reappears on the other side, the same goes for the colors. That kind of kills the illusion.
So I made the generated bitmaps bigger than the shown ones. I generate 4 bitmaps of 1024 by 512 and show them in a frame of 800x200.

http://jsfiddle.net/LwDC9/5/

vrijdag 2 mei 2014

Error Handling for minified javascripts.

Why we minify

Javascript is often minified for production. This is also called 'uglification' sometimes. It means your javascript  is written like one long line.

What is the problem?

Minification can sometimes cause errors. It's hard to see if you made an error, or the minifier.
Sometimes an error just happens. We're not perfect.
In a minified file you'd get an error in your console like:
 Uncaught ReferenceError: faultyReference is not defined script.js: 2
When line 2 is 4000 characters long, it's a little heavy. Especially since most minifyers will also minify the variable faultyReference to something like: a132.


New standard fixes the problem

In the new standard for the window.onError event you don't just get a line, but also a column.
You can generate an error message for yourself:
 Uncaught ReferenceError: faultyReference is not defined script.js: line 2, col 3704
Now you know exactly where to debug...

Tell me how

Ok!
  1. start of 2014 this was working in Chrome. I don't know about other browsers, but if all else fails, develop in Chrome (I think it's the best development browser anyway) 
  2. before you execute any other script add something this:
 window.onerror=globalErrorListener;  
 function globalErrorListener(msg, url, line, col, obj)   
 {  
      console.log('--' + msg + ' ' + url + ': line ' + line  
      + ', col ' + col);  
 }  

Now in your console, you'll find the exact column where the error occured.
The obj is the stack, you can also log that, just add it to the string.

Tadaaa! And thank you chrome for implementing so fast. Hope this helps someone, it sure helped me!
more about this

zondag 2 maart 2014

Scripts generating scripts - javascript and illustrator

I think I've found a new workflow that may not be new, but might be new to some.
I had the problem of having to generate a lot (3800) of files in illustrator.
These files had elements that would be generated  (by Flash) and had to be integrated into ai files.
Also I had to present it in HTML5 using x3Dom to get an idea of what I was doing.

Now I had made a as3 program, that took in 3D data from Rhino. (We just exported point and bi-arcs in text from Rhino) My script in Flash converted this data into 2D files vector that could be used as textures (when stamped down to PNG's).
We used the PNG-textures for the preview in HTML5, so we could walk through the textured building (this was for an architect), but we also needed the (vector) textures to be saved in a format that a printer could work with, we setlled on PDF, which I could generate from Flash with a library..

First step: generating JS from Flash for a Preview:
I had already interpreted the bi-arcs in Flash, so to do it again in Javascript wouldn't be much of a problem, but it turned out to be easier, to generate the javascript from Flash.
This way, I could spend my time elaborating on the data where I needed it and and leaving out what wasn't important.

Second Step: generating a JS script to generate files in Adobe Illustrator:
Although we first decided the output would be PDF, because the library did not export layers in the PDF page and because spot-colors were a problem, it turned out to be easier for the printer to get AI files instead.
I was able to comply, by doing the same trick again. I used Flash, to generate Javascript (JSX) that extends adobe illustrator and uses it to generate illustrator files.
(My basic generation script, without the parts generated by Flash is below)

This last step seems a quite promising development. We could go from Rhino (a scripted environment) to Flash (a scripted environment) and then use Illustrator to generate print-ready files (in again a scripted environment).
This means, that this workflow could be very helpfull for anyone with the same kind of problem.

Photoshop, In Design and Illustrator all support javascript extensions for scripting. In stead of going through actionscript (flash) to generate the scripts to extend illustrator, I could have used Javascript to generate the same. Also Adobe makes a point of supporting applescript and VBscript as well.
This enables the developer (or scripter) to do his work and most of the debugging in the environment he's most comfortable with and then exporting to whatever environment he wants. It may seem a bit cumbersome at first, but I assure you, once you get your head around it, it's VERY flexible.

One word of caution: Debugging jsx in illustrator sucks. So get a working script and let your script modify it to just add the data.

Here is a tutorial to get you started:
http://creativedroplets.com/tutorial-scripting-for-illustrator-cs6/

There is a LOT of support for scripts from adobe:
http://www.adobe.com/devnet/illustrator/scripting.html

And it's actually well documented this time. It only took me a few hours to write my generation script, which was my first script ever.This was a very nice surprise. Even though I'm not all that familiar with Adobe Illustrator, I had no trouble finding specific things like information about layers and spotcolors. I actually learned a few things about the way illustrator is put together.

I've bitched about Adobe's lack of vision in the past when compared to the things Macromedia used to do (and I'm still behind everything I said), but this seems a very promising new direction, which could result in a very active community.
When something is good, it needs to be said as well: Well done Adobe.

Just to be complete, here is my basic rendering and generation script.
I use Flash to create the data this script will use to generate ai-files, with two layers and two spot-colors.
It's been scrounged together from various sources offcourse, but it will tell you all you need to do, if you just want to generate ai-files by drawing paths into them.

To get you started, copy it into a text-file. name it jsx. The go to illustrator, choose scripts from the menu.
Navigate to the script and select it.
It will ask you to find a directory and it will put three files in it with generated content.
It's well commented, so it should be enough to get you started on your own.
If you like it, drop me a comment, to tell me what you made :)

/**********************************************************

Basic Generation script for illustrator made by Hjalmar with Flash...

*********************************************************/

/** 
 Creates a new document, 
 draws a baffle and 
 Saves every document as AI
*/

// Main Code [Execution of script begins here]

try {
 
 // Get the folder to save the files into
 var destFolder = null;
 destFolder = Folder.selectDialog( 'Select folder for AI files.', '~' );

 if (destFolder != null) 
 {
  var options, i, activeDoc, targetFile; 
  
  // Get the PDF options to be used
     
  for ( i = 0; i < 3; i++ ) 
  {
   // create a document!
   // Preset
   var doc_preset = new DocumentPreset;
   doc_preset.units = RulerUnits.Centimeters; // normal is .Inches;
   var activeDoc = app.documents.addDocument(DocumentColorSpace.CMYK, doc_preset); // add document
         
   // Get the file to save the document as ai into
   targetFile = this.getTargetFile("baffle_"+i, '.ai', destFolder);
   
   // set up the layers!
   var plotterLayer = activeDoc.activeLayer; // there's one made automatically, so we use that one... activeDoc.layers.add();
   plotterLayer.name = "cutcontour";
   var artLayer = activeDoc.layers.add();
   artLayer.name = "stationsblauw";

   // create all colors
   // Define the new color values in CMYK, but we are going to make them spot colors!
   CMYKblue = new CMYKColor();
   CMYKblue.black = 50.0;
   CMYKblue.cyan = 80.4;
   CMYKblue.magenta = 0;
   CMYKblue.yellow = 0;

   CMYKline = new CMYKColor();
   CMYKline.black = 0;
   CMYKline.cyan = 0.0;
   CMYKline.magenta = 32;
   CMYKline.yellow = 32;
   
   // Use the CMYK color object in the creation of spots
   // Create the new spots
   var blauwspot = app.activeDocument.spots.add();
   blauwspot.name = "stationsblauw";
   blauwspot.tint = 100;
   blauwspot.color = CMYKblue;
   
   var linespot = app.activeDocument.spots.add();
   linespot.name = "cutcontour";
   linespot.tint = 100;
   linespot.color = CMYKline;
   
   // Create a spotcolor objects, set the tint value,
   var spotBlue = new SpotColor();
   spotBlue.spot = blauwspot;
   spotBlue.tint = 100;

   var spotLine = new SpotColor();
   spotLine.spot = linespot;
   spotLine.tint = 100;

   // set the outline path as part of the plotterLayer!
   
   // Use the spot color to set the fill color
   var myLine = plotterLayer.pathItems.add();
   //set stroked to true so we can see the path
   myLine.stroked = true;
   myLine.strokeColor = spotLine;
   myLine.closed = true;
   myLine.setEntirePath([[220, 475], [375, 300], [200, 300]]);

   for(t=0;t<10;t++)
   {
    // draw a square on a random place on the artLayer
    var tbp = artLayer.pathItems.add();
    tbp.stroked = false;
    tbp.filled = true;
    tbp.fillColor = spotBlue;
    var tx=250+Math.random()*50;
    var ty=250+Math.random()*50;
    tbp.setEntirePath([[tx, ty], [tx+5, ty], [tx+5, ty+5],[tx, ty+5]]);
   }
   // Save as ai
   var saveOptions = new IllustratorSaveOptions();
   saveOptions.compatibility = Compatibility.ILLUSTRATOR8;
   saveOptions.flattenOutput = OutputFlattening.PRESERVEAPPEARANCE;
   app.activeDocument.saveAs( targetFile, saveOptions );  
   
   // we close the doc to save memory!
   app.activeDocument.close();
   
   //alert( 'Document saved as AI' );
  }
 }else
 {
  throw new Error('No folder selected');
 }
}
catch(e) {
 alert( e.message, "Script Alert", true);
}


/** Returns the file to save or export the document into.
 @param docName the name of the document
 @param ext the extension the file extension to be applied
 @param destFolder the output folder
 @return File object
*/
function getTargetFile(docName, ext, destFolder) {
 var newName = "";

 // if name has no dot (and hence no extension),
 // just append the extension
 if (docName.indexOf('.') < 0) {
  newName = docName + ext;
 } else {
  var dot = docName.lastIndexOf('.');
  newName += docName.substring(0, dot);
  newName += ext;
 }
 
 // Create the file object to save to
 var myFile = new File( destFolder + '/' + newName );
 
 // Preflight access rights
 if (myFile.open("w")) {
  myFile.close();
 }
 else {
  throw new Error('Access is denied');
 }
 return myFile;
}

dinsdag 11 februari 2014

Rotating a point in 3D

It seems so trivial in this age of OpenGL, WebGL and many other beautiful libs, that will do the hard work for you. And then you find yourself in a position, where you need something simple and it's nowhere to be found.

Rotation of a point around the origin or O  or {x:0,y:0,z:0}
How hard can it be.
Well, it's not simple.

Here is the code in as3 and javascript

function rotatePoint(p,rx,ry,rz)
{
    var x,y,z,q={};
    x=p.x*Math.cos(rz)-p.y*Math.sin(rz);
    y=p.x*Math.sin(rz)+p.y*Math.cos(rz);

    q.x=x*Math.cos(ry)-p.z*Math.sin(ry);
    z=x*Math.sin(ry)+p.z*Math.cos(ry);

    q.y=y*Math.cos(rx)-z*Math.sin(rx);
    q.z=y*Math.sin(rx)+z*Math.cos(rx);
    return q;
}

The parameters:
p is a point, so an object with {x:x,y:y,z:z};
rx is the amount you want to rotate around the x axis in radians.
ry is the amount you want to rotate around the y axis in radians.
rz  is the amount you want to rotate around the z axis in radians.

It returns a point with the new rotated coordinates. Don't try to understand the maths, it took me three days to put this together.

So in practice, I have a point 1,0,0 and I want to rotate it around the z axis 45 degrees.
The answer is in this case pretty obvious, it would be 0,707...,0.707....,0 or cos(45),sin(45),0
So how would we go about doing that with the function?

  p.x=1;
  p.y=0;
  p.z=0;
  p=rotatePoint(p,45/180*Math.PI,0,0);
  trace(p.x+","+p.y+","+p.z);

Output:
0.7071067811865476,0.7071067811865475,0

Halleluja, you can now play around with the other axis and stuff.
Any time you need something rotated, this function is your friend.
I've been using it on an off since 1988 just needed it again for my Delft project (about which I will tell you more later, but now, I'm sworn to secrecy :)
I found it in an ancient piece of code from 1996 in C, so I rewrote it to Javascript/As3.
And there you are.

donderdag 2 januari 2014

Hybrid Platform. HTML5 and Flash Games.

2013 saw the birth of the “Hybrid Game Platform”. This platform is basically a compatibility layer written simultaneously in Flash and Javascript.

This means, you can write game code once and export as Flash and HTML5. Now this may seem unimpressive, as adobe claims the same thing with createJS. But the fact is, that there needs to be a lot of conversion, before your game works again.

With the Hybrid platform we are talking the same language in both cases. The main advantage of this is, your choice of platform is now a lot wider.
Mobile platforms have a very limited support for Flash, but older browsers don't support HTML5.
The Hybrid platform analyses the browsers capabilities and chooses the right techniques to display.

This is best practice anyway, but used to mean, you had two versions of the software that had to be written.
And if you change anything (like texts, logo's etc) you have to change it twice. This lead to more cost.
With the deployment of the hybrid platform, this cost is literally cut in half, because you only have to do everything once.
Also, by keeping Flash as an option, you can then convert the Flash-apps to Mobile Apps quite easily.
All round flexibility for a very low price.

The Hybride Platform has been succesfully deployed for three different clients in 2013.
(Sinterklaasjournaal (just HTML5, no flash fallback), AanZee vakantiehuizen, VillaXL).

I will add links when these go live 15th of  januari 2014!

Hybrid Site Platform
I'm now working on a similar platform for sites.