Latest Entries »

Augmented Reality Facebook App

The app in action

The app in action

Web Science Experimental Project

Web Science for whom I work here in Italy is a communications agency with a strong focus on research and strategy. We get lots of opportunities to develop new skills by doing experimental projects in our career development time. The MyJournal app planned as an experimental project to expand our skill set and root out any problems or issues related to Facebook programming.

Me and another programmer, Mirko Longhi worked together on this experimental project for Web Science, and I want to give credit to Mirko for the original idea for this app.

What does the app do?

The app gives you the opportunity to create a custom newspaper cover story featuring one of your friends (or yourself). The next step allows you to print out an Augmented Reality marker which you can then use to literally hold the custom newspaper in your hands. You can then snap a photo of you with the paper in your hands and post that picture on your friends wall. A photo album is also created to hold all of the images you create with the app.

How does the app work?

The structure of the app basically consists of 3 parts. Customizing a newspaper cover, posing with your newspaper, and finally, posting your photo to your friends. When we started off, me Mirko Longhi took one of the first two phases each. At the time, I was the only one with Facebook code experience (which I learned from Emanuele’s blog) and so I took part one, while he took part 2. Part 3 would be handled later by both of us.

Part 1 – Customizing the newspaper - If you have tried the tutorials on this blog you will know how to get permissions and get information about the user. With this information in hand I created a simple form with an image of the newspaper on the right. The only part of the form that uses Facebook user info is the drop down with all the friends names. This is a simple way to choose a friend and while I did experiment with some Auto-Complete tutorials and source code I found it too complicated (and buggy) for the task.
Using the Graph Api, I can now use that friend’s ID to get their profile image and put it, along with a title and text, into the newspaper template. For all of the image manipulation tasks I used an open source PHP library called WideImage. I use this to put white squares over the placeholder text on the paper, to position and resize the profile photo and to eventually save that image to our server.
Wide Image is great and so easy to use. I did have to research a bit deeper to create a multiline textbox, however, and found a solution by a guy called SK89Q.
With the newspaper fully prepared, I pass the location of the image to the next page where Mirko was handling the Augmented Reality part.

Part 2 – Augmented Reality snapshot - Using the FLARToolKit combined with Papervision (the standard setup) we take the image from part 1, apply it to flat 3D plane object and orient that object according to the AR marker being read by the webcam. When the user snaps a photo of themselves, the image data is converted to base64 text and sent to the next page as a variable On the following page the image can be decoded and saved using PHP’s imagecreatefromstring().

Part 3 – Posting the image - The very first prototype had all the photos being hosted from our work server. We later decided that this would be a big drain if the app became popular and decided to create an album for our app’s photos. The album is great as it creates a permantent location for all of the photos where they can be commented and liked, furthering their viral capability. This was actually quite easy and only required a bit of extra work. We needed to add photos and albums to the permissions that the app asks at the start. We also put put a link back to the app in the description of the album. Along with an album, the photo is also posted directly to the chosen friend’s page using CURL (again, something I learnt from Emanuele’s blog).

What problems did we encounter

Well the first major problem was our own server, which was not running the right version of PHP for the Facebook php class. To keep the pace going I developed on my own webspace for a while.
There are also some funny bugs that people should be aware of regarding Internet Explorer. Explorer was blocking cookies in an iFrame when the top page was on a different domain. After much searching I found the solution was to set a particular header with PHP .
Another Explorer problem I had was image caching. Because the user can use the preview function to continually change the same image, IE was always presenting the same cached image from the first time it loaded. I fixed this by applying a random number variable to the end of the image location.

What would we like to improve

At the moment the 3D newspaper turns out quite pixellated and I am not sure why. The image that I pass to the flash is good resolution, so I think it will be a matter of playing with the 3D settings and maybe looking into another Flash 3D solution (UPDATE: It was just a matter of setting a smooth parameter on the bitmapTexture object).
I also worry that the app may become too slow when there is a load on the server as WideImage is not known to be fast. To fix this I may need to rebuild using PHP’s native image manipulation classes which are more difficult to use but should be faster.
And when I have time I want to have language selection at least for english.

Try out the Web Science MyJournal app.

My First Appcelerator App continued…

Cookie-Twitter Mobile App

Cookie-Twitter Mobile App

A little while ago I posted that I was experimenting with Appcelerator. I had combined 2 different tutorials that I had found to create a fortune cookie app that opens to randomly reveal 1 of a bunch of tweets. While I don’t claim to be an expert I am posting the source with my comments only because it was requested. Usually I would prefer to have a bit more experience before making a tutorial.

I also regret that I will not show you how to setup Appcelerator to successfully output for iPhone and Android. The process is well documented in other places and to be honest the hoops you have to jump through to do stuff with Apple gives me a headache :P

The code is relatively simple. The toughest part is getting your mind around the way that the JS framework for Appcelerator works. The order that tasks are carried out in etc. While this project could be done out without the constructor functions grouping the code, it is a lot tidier this way and more flexible when you have multiple windows and you want to refresh. The only way to refresh a window in Appcelerator is to run the code again on a “FOCUS” event.

So here it is, I hope it is helpful.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
//Detecting if this is an iPhone as it will change the way we do random numbers
var HAS_BAD_RAND = Ti.Platform.osname.match(/iphone/);
 
//Creating the native Window UI element in which to put our graphics and text
var win = Ti.UI.createWindow({ backgroundColor: '#ffffff' });
 
//Opening a link to Twitter and storing the results in a Network Object called loader
var loader = Titanium.Network.createHTTPClient();
loader.open("GET","http://api.twitter.com/1/statuses/user_timeline.json?screen_name=aziraphael&count=10");
 
//Creating the variables we will be using including all graphic holders and the array
var fortunes = [];
var closed_cookie, opened_cookie, opened_cookie_image, paper, new_cookie_button;
 
//The function that is called once the tweets are loaded
loader.onload = function() 
{
    //Feed the tweets into our array
    var tweets = eval('('+this.responseText+')');
    for (var i = 0; i < tweets.length; i++)
    {
        var tweet = tweets[i].text;
        fortunes.push(tweet);
    }
 
    //Run our constructor functions
    createElements();
    assignBehaviors();
    arrangeElements();
    win.open(); //Opening the window practically opens the app
};
 
//Our constructor functions are arranged for tidyness
function createElements()
{
    //Our closed cookie image view (an apple term for the image container)
    closed_cookie = Ti.UI.createImageView({
        image: 'closed_cookie.png',
        width: 'auto',
        height: 'auto'
    });
 
    //An empty view to store the open image and text
    opened_cookie = Ti.UI.createView({
        width: 300,
        height: 234,
        visible: false
    });
 
    //The actual opened cookie image
    opened_cookie_image = Ti.UI.createImageView({
        image: 'opened_cookie2.png',
        width: 'auto',
        height: 'auto'
    });
 
    //The text box in which the tweets are written
    paper = Ti.UI.createLabel({
        color: '#000000',
        font: {fontSize: 12, fontFamily: 'Courier'},
        width: 150,
        height: 'auto',
        top: 25,
        left: 40,
        opacity: 0,
        textAlign: 'left'
    });
 
    //A native iPhone or Android button
    new_cookie_button = Ti.UI.createButton({
        title: 'New Fortune Cookie',
        width: 200,
        height: 50,
        bottom: 25,
        visible: false
    });
}
 
//Setting up the event listeners
function assignBehaviors()
{
    //If the cookie is clicked on
    closed_cookie.addEventListener('click', openCookie);
 
    //If the "new cookie" button is clicked on
    new_cookie_button.addEventListener('click', newCookie);
 
    //If the phone is shaken (same result as "new cookie")
    Ti.Gesture.addEventListener('shake', toggleCookie);
}
 
//Toggle between open and closing cookie
function toggleCookie( ev )
{
    opened_cookie.visible ? newCookie() : openCookie();
}
 
//Set up a new cookie
function newCookie( ev )
{
    paper.opacity = 0;
    opened_cookie.hide();
    new_cookie_button.hide();
    closed_cookie.show();
}
 
//Opening the cookie
function openCookie( ev )
{
    closed_cookie.hide();
    paper.text = getFortune();
    opened_cookie.show();
    paper.animate({opacity:1, duration:500}); //Fade tween of paper
    new_cookie_button.show();
}
 
function getFortune()
{
    //Get a fortune using custom random function
    var rand = random( 0, fortunes.length - 1 );
    return fortunes[ rand ];
}
 
//Custom random function
function random( min, max )
{
    //Because of a bug in iPhone random numbers, the number
    //is determined using the time as a random seed-
    min = min || 0;
    max = max || 1;
    if (HAS_BAD_RAND){ max += 1; }
 
    var secs = (new Date()).getTime();
    var rand = min + Math.round( Math.random( secs ) * (max - min) );
 
    return HAS_BAD_RAND ? ( secs % max ) : rand;
}
 
//Adding all the visual elements to the window in the right order
function arrangeElements()
{
    opened_cookie.add( opened_cookie_image );
    opened_cookie.add( paper );
 
    win.add( closed_cookie );
    win.add( opened_cookie );
    win.add( new_cookie_button );
}
 
//Initiating the whole process by sending the loader request
loader.send();

Working Efficiently

My Tips for Productive and Efficient Working

Recently during my work evaluation and career planning that we do every 6 months or so, I was told that I am considered to be the most productive worker amongst the Creatives. I can honestly say, without false modesty, that I was surprised. Yes, I do get my work done, and don’t miss deadlines, but at the same time I almost never feel rushed or pressured, and rarely stay back late, especially compared to my previous work. My interest piqued, I was more than happy when they asked me to prepare a presentation about my process as it gives me an opportunity to learn more about something that is coming quite naturally to me at the moment. First off, let’s look at a bit of background and context.

Background and Context

I worked in the advertising industry for 5 and a half years in two of Sydney’s biggest agencies, M&C Saatchi and Ogilvy. I have worked on many big clients including Coca Cola, Qantas, St.George Bank and Telstra. Between demanding clients and pitchwork I have worked my fair share of late nights and cramped timelines. Whilst projects would get out of control sometimes and clients would demand the impossible, in general there was always a very sound organizational structure in place and a lot of people dedicated to planning.

I moved to Milan, Italy to find myself in two firsts. One was working in a new country of course, and the other was working in a smaller agency. With much less explicit organization and planning taking place, I have been doing a lot of it myself within my usual workflow. Let’s have a look at some of the tips I found that would be of most benefit to anyone who needs to self manage.

An example of folder structure

An example of folder structure

A Tidy Workspace (virtual and real)

Folder Structure – Without a stable central server (they have one for fileswapping but do not use it for long term storage), everyone at my current work basically has their own folder structure. While I thought this was strange I had no problem adapting and organizing my files and folders based on the predefined structure I was used to in large agencies. Whilst there are bound to be many decent solutions, you NEED to have a system that keeps a record of all your source files, all your exports and build. It needs to keep source materials separate from your own work, and inspiration or asset materials separate again. It needs to do all this whilst being easy and logical to navigate

Desktop (virtual) – I never can stand to see a messy desktop with a hundred different icons strewn about. Everybody will build up links, files and other icons over time (I do), the important thing to know is when you are done with them. I always keep a “Desktop Clutter” folder round where I throw stuff that I may need again, but in all likelihood am done with. As far as I can remember, I have had to delve into it 4 or 5 times in my life.

Desktop (real) – Maybe I am just a little bit OCD, but I can’t stand messy working spaces and I see no reason why they should exist. Once again, I understand that things can pile up in time, but at least make a neat pile. I am convinced that having papers and other junk strewn around is detrimental to your productivity.

Tidy Program Layouts – Whether you use Photoshop, InDesign or even Word, there is no reason to have menus and control panels strewn around your virtual workplace. All these programs have great tools for creating predefined layouts. Take the time to organise your workspace and you will always know where your tools are for faster working

Tidy Files – When you are rushing it can be the easiest things in the world to forget, but organizing the internal of your files is critical for fast and efficient working. Especially important if you ever need to pass the file over to someone else, and just for your own sanity, it helps to have proper layer names, groups, smart objects, layer comps and artboards setup. In the case of layer comps and artboards, it can greatly decrease the time it takes to export your designs. Take a few minutes every half hour to make sure your file is not becoming a mess.

Planning

I always plan out a project before I start. That may sound time consuming, but depending on the size of the job, it can just be a mental plan with a few scribbles jotted down or a full step by step description of task sent by email to those I am working with. In this way, no one is surprised about what needs to be done and if I need help, I already have a list of specific task that someone can jump in on.

Steps and lists are great for keeping track of your progress, not falling behind and for identifying potential trouble spots. Part of planning can also include searching out solutions to these trouble spots before you get to them. Whether it be finding a tutorial on reading XML with Actionscript or searching out a selection of photoshop brushes, if you find solutions before you come across the problem, your workflow won’t be interrupted.

Any found resources, templates, tutorials and reusable components are almost always going to be useful again sometime. For this reason, it is always great to have a “General Assets” folder to put them all in. The number of times I have reused the iPhone elements psd or the Greensock tween classes for as3, it would have been a real hassle to always be searching around for them again.

Doing the Actual Work!

And now for the tough part, getting the work done. Here in no particular order are some of the things I have learned about getting work done

Early stages – When concepting and designing it is important in the brainstorming and sketching stage to get your ideas onto paper and not dwell too much on each one. Details will come later and with the idea on paper, you aren’t going to forget about it. Spending too much time developing one idea or layout in this stage prevents other possibilities from coming forth. After this initial stage it is a good idea to seek advice with your different options from someone else (boss or trusted colleague) to further define your options.

Use your energy well – We all know that we have different times of the day that we are working at 100%. And NOBODY works at maximum capacity all the time. The important thing is to use all of your time well. Those hours of the day that your attention drifts and you become tired are great for tying up lose ends, tidying up files and folders or even researching for solutions you can use for tomorrows work. This way when you get your best hours, you can use them to maximum effect and not be bogged down by the little things.

One of my distractions

One of my distractions

Distractions can be your rewards – No one is expected to work at maximum capacity for every hour you are at work. It is only natural to want to check that facebook page, or read that article on Wired.com. I find to have any of these pages open behind my work is too much of a distraction, so I close them all down and give myself little breaks that I earn. Set yourself a mini objective before you get your mini reward, for example, “I am going to design three different button styles for this site before I check my status comments”… Well ok, no one ever comments on my status, but you get the idea.

Don’t become obsessed with details – There is not just ONE perfect solution to your problem. You may have already found 3 optimal solutions, and by procrastinating over that border thickness you are just making excuses to move on to the next stage.

And if you really are blocked – Don’t be afraid to get an outside opinion from a colleague or boss, they may just see something that you can’t because you are too close to the project.

Speaking of feedback – Try to organise feedback and review sessions with all relevant stakeholders. Anyone who is likely to have an opinions should be seeing your work all together. This is not always possible, but the more you can do it, the more comprehensive your feedback is and the less conflicting it will be.

After the Project

After every project, even if it is just in your own head, it is important to have a bit of a debrief. Look at what went well, what went wrong. Are there any new procedures that should become part of project workflow? What could you have done better and what could other people have done better to help you. Did you receive assets to late to complete on time? Did you get distracted writing a blog post and deliver your work an hour late? The important thing is to be open and honest and to give and take constructive criticism with maturity.

My First iPhone / Android app with Appcelerator

Using Appcelerator to code cross platform mobile apps

Cookie-Twitter Mobile App

Cookie-Twitter Mobile App

Appcelerator offers a JavaScript framework to interface with the native Xcode and the Android SDK. It gives access to native UI elements of both devices which allows for much quicker development times and a more familiar experience for users. This sets it apart from other solutions like PhoneGap and Corona (which each have their own strengths and weaknesses).

As I am still learning to use Appcelerator and don’t intend to do a tutorial until I can really understand it a bit better (and can offer something original). I would like to share however, a combination of two tutorials that I made and like well enough. Both tutorials are from MobileTuts+, a great resource for learning to code mobile applications and content. The first tutorial deals with making a fortune cookie app that is completely cross platform compatible between android and iPhone. The second tutorial that I used is all about feeding twitter data into mobile apps. All I did is combine the two to randomly search my twitter feed to collect and store a bunch of tweets. The fortune cookie then randomly selects a tweet to display when you shake the app (breaking the cookie). Like I said, I will make a proper tutorial when I feel more comfortable with the code and can explain it better.

GreenJay Animated Twitter Reader – Full Source

Animated twitter visualization ready for your projects

Screenshot of the twitter reader

Screenshot of the twitter reader

One of my first ever posts on this blog was regarding twitter integration in AS3. I later refined the program and used it for my Merry Twitsmas animated card which read all the tweets using a #dearsanta hashtag. I then used the same code and idea to build a custom Christmas card for the company I am working for.

I have had a lot of fun with this project that actually started off as my first AS3 project and I would like to share the source code. I have all the classes commented, stripped out some of the unnecessary bits and pieces and generally tried to make it into a neat little package. This version can be seen here, and while it features tweets that fly across the screen it can be easily adapted for them to stay on the screen and build a scene like in the Twitsmas star scape.

The project consists of a fla file, which has no code in it, only a few assets. There is a main class a Twitter class that is used to draw the content from Twitter and a Tweet class for each of the tweets that includes all the information relevant for each tweet. So feel free to download and use the full source code for the Twitter AS3 Reader. If anyone makes anything cool with it let me know and I’ll post it.

Playing Blind

Terry Garrett plays through Abe’s Exoddus despite blindness

After reading an interview with Terry Garrett on Oddworld.com I couldn’t help but make a quick blog post. Terry Garrett, with a bit of help from a friend or his brother to navigate menus or describe a cut scene, is able to play through all of the Oddworld classic, Abe’s Exoddus. He is able to do this with the Oddworld game better than most for a couple of reasons. Firstly, Abe makes a sound for every interaction he has with the environment, from talking with other characters, to bumping his head. And secondly the game, whilst exploring some very complex puzzles and interaction is relatively simple. Abe’s steps are all the same, the screen is always a set number of steps across and the position of objects can be easily memorized and visualized by Terry’s mind’s eye. This combined with the fact that Exoddus has a quicksave feature as I expect he dies a lot as he learns the layout of each screen.

I find this story fascinating on a couple of levels. First off, from a game design perspective, without meaning to, the folks at Oddworld Inhabitants have made the game playable for a blind guy. How awesome is that!? The details they have put into all the different sounds, including the music which is used to convey imminent danger, all help to create the scene. The second interesting thing is that Terry can actually navigate 3D game worlds with a bit of help. With sound design in 3D spaces being what it is today combined with a create speaker system, Terry can create a picture in his head of the virtual game world just from the sound.

I leave you with a playthrough / interview with Terry of one of my favourite games, Abe’s Exoddus.

A bit of inspiration

The Third and the Seventh by Alex Roman

Getting time to post these days is becoming more and more difficult what with being a dad. Every day however I check my RSS feeds and see fantastic works of art, great ads and interesting social ideas. With this in mind it makes sense that when I don’t have time to post a tutorial or a piece of my own work that I will post great inspiration works that I find around.

The first in my “Inspiration” series is a little old, but always makes me want to get out there and do something creative. It is called “The Third and the Seventh” named after the third art (according to the French) of Architecture and the seventh art of Cinema. It is entirely created from scratch by computer graphics and post production software and it is a beautiful and loving homage to the two artforms. It also uses one of my favourite pieces of music, “The Departure” by Michael Nyman which you may recognise from the film Gattaca.

I have a lot of respect for great Architecture and would love to see this guy on board if they ever made a film of The Fountainhead by Ayn Rand.

The video

And the “Making Of” Video

If you are like me and find it hard to believe it is 3D graphics

Merry Twitsmas Everyone!

Merry Twitsmas from GreenJay Blog

Merry Twitsmas from GreenJay Blog

A little christmas themed twitter visualization that I cooked up. You can change the twitter hash tag that is being searched by changing the ?key=dearsanta at the end of the URL string. In this way it can be used for any language (you could put index.html?key=buonnatale to make it italian for example).

I used the very cool Snow class from FlashAndMath.com and for the background I was a bit lazy and modified a desktop background from Vladstudio. Yeah I am a bit busy these days, sorry Vlad :)

Anyways, I hope you all like it. When I get time I will try to do a little tutorial on the Twitter API which I used to bring in all the tweets.

And once again, have a very merry Christmas.

Recently at work I was asked to create a project in AS3 with some very specific requirements. The idea is to create a series of number generators to help users choose Lotto numbers. There will be various generators, each using different methods of finding numbers, based on inputs from users. The special needs part is that the algorithms and functions involved in finding the numbers need to be done in Javascript. The reason is because we will be creating these generators in different environments and platforms, across Facebook and mobile, and it will be nice to have just one set of methods to call.

I haven’t had the need to call a javascript function from flash in quite a while, so I was pleasantly surprised to find the ExternalInterface class. More so when I saw how robust it was and easy to use. Here is the Actionscript for getting an array of unique lotto numbers from a range of 1-90. It is very clean and simple.

1
2
3
4
5
6
7
import flash.external.ExternalInterface
 
var numbers:Numbers = new Array(); //The array we will store the numbers in
 
//Set the numbers array to the return value of the getLottoNumbers
//javascript function. We pass a variable of 7, the number of numbers we want.
numbers = ExternalInterface.call("getLottoNumbers", "7");

Here is the javascript that we are calling.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
//PRIMARY FUNCTION
function getLottoNumbers(num) 
{
    var numStore = new Array();
    numStore = getNumStore(90); //Get a store of the numbers 1-90
 
    var numbers = new Array();
    for(var i=0; i<num; i++) //Get random numbers from array and remove them
    {
        var tempNum;
        tempNum = randomXToY(1, numStore.length-1);//Choose random index
        numbers[i] = numStore[tempNum];
        numStore.splice(tempNum,1); //Remove the number from array
    }
    return numbers; //Return the array
}
 
 
// FUNCTIONS USED BY THE PRIMARY FUNCTION
 
// Function to get random number between min and max
function randomXToY(minVal,maxVal,floatVal)
{
    var randVal = minVal+(Math.random()*(maxVal-minVal));
    return typeof floatVal=='undefined'?Math.round(randVal):randVal.toFixed(floatVal);
}
 
// Returns an array full of the numbers to pick from
function getNumStore(maxNum)
{
    var tempArray = new Array();
    for(var i = 1; i<= maxNum; i++)
    {
        tempArray[i] = i;
    }
    return tempArray;
}

The only other thing to note is that for the Flash to be able to access the javascript, it has to be included in the html file the holds the flash.

1
<script type="text/javascript" src="scriptFile.js"></script>

Unity3D – An Introductory Tutorial

Unity3D is a platform for creating real-time, interactive 3D (I could have just said games, but I wanted to be more general). Not only is it easy to use and learn, but can be exported for practically every platform under the sun (iPhone, Android, PC, Mac and even an browser web player). Although I have only made a simple tutorial, I gather from the range of projects out there, that it is just as robust as any development program.

Brick Blaster

The little “game” I want to show you how to make is basically shooting balls at a wall of blocks. A simple concept, but potentially the basis for an entire game. What we will need is a floor, a camera, a light, a wall made of separate blocks and our balls to shoot at the wall. The balls and the wall are going to be created with code, but the rest of the elements will be setup in Unity’s 3D editing environment. Creating the elements is pretty straight forward. The floor is created from the menu with GameObject > Create Other > Plane. I have also created an empty object called SpawnPoint to attach our wall to.

Unity3D scene from top view

Unity3D scene from top view

In order to create game objects from code, they need to exist in the library as “Prefabs”. This is how to create a prefab, directly from the site.

  1. Choose GameObject->Create Other->Cube
  2. Choose Component->Physics->Rigidbody
  3. Choose Assets->Create Prefab
  4. In the Project View, change the name of your new Prefab to “Brick”
  5. Drag the cube you created in the Hierarchy onto the “Brick” Prefab in the Project View
  6. With the Prefab created, you can safely delete the Cube from the Hierarchy (Delete on Windows, Command-Backspace on Mac)
Unity3D project view of all assets

Unity3D project view of all assets

With these prefabs in our library, we can now “Instantiate” those objects dynamically in the games runtime. For this game we want to achieve 3 different functionalities, and we will have 3 scripts for that. One script will build the wall, and will be attached to the empty SpawnPoint object. Another will control the aim of the camera with the arrow keys, and the final will control the firing of the balls from the point of view of the camera. Now lets take a look at our 3 scripts. All three are in JavaScript, but you can code in a few different languages, and even chop and change between languages within Unity. I will show the scripts first, with code comments, and then I have a few notes for the end.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
//To be attached to the Main Camera
var moveSpeed : int; //The speed of camera movement
 
//The Update function is run every step or frame of the game
function Update () { 
    //The following 4 if statements test if the arrow keys are being
    //pressed and rotate the camera in the right direction
    if (Input.GetAxis("Horizontal") > 0) {
        //In unity, transform refers to the object to which the script
        //attached. Essentially like referring to "this" in javascript
        transform.Rotate(Vector3.up * Time.deltaTime * moveSpeed);
    }
    if (Input.GetAxis("Horizontal") < 0) {
        transform.Rotate(Vector3.down * Time.deltaTime * moveSpeed);
    }
    if (Input.GetAxis("Vertical") > 0) {
        transform.Rotate(Vector3.left * Time.deltaTime * moveSpeed);
    }
    if (Input.GetAxis("Vertical") < 0) {
        transform.Rotate(Vector3.right * Time.deltaTime * moveSpeed);
    }
}

The axis mentioned above is basically an input and is defined in Edit > Project Settings > Input. Unity has preset most inputs that you would want, and is quite clever about how they are setup. Each input has backup keys, sensitivities and all sorts of other stuff that I don’t understand yet. When they say Axis though, it should be understood that it includes a control that works in two different directions. For example, the left and right keys (and as a backup the A and D keys) are represented by the “Horizontal” axis. To test if the Horizontal is going left or right, we test if it is positive or negative.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var bulletPrefab : Transform; //The bullet object
var shootForce = 10.0; //The force of the bullet
 
//Our function to instantiate and fire a ball
function FireRocket () {
    //Instantiate the object at the cameras position
    var instanceBullet = Instantiate(bulletPrefab, transform.position, Quaternion.identity);
    //Add a force to the ball in the direction the camera is facing
    instanceBullet.rigidbody.AddForce(transform.forward * shootForce);
}
 
// Calls the fire method when holding down ctrl or mouse
function Update () {
    //Test if the fire1 button has been pressed
    if (Input.GetButtonDown("Fire1")) {
        FireRocket();
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
//Attached to the SpawnPoint empty object
 
//This is left variable and is defined in Unity's user interface
var prefab : GameObject; 
var gridX = 5; //How many columns
var gridZ = 5; //How many rows
var spacing = 3; // Space between rows and columns
 
//The Start function is called when the object enters the scene
function Start () {
    for (var z = 0; z < gridZ; z++) {
        for (var x=0;x<gridX;x++) {
            //Create a position variable based on the position of SpawnPoint
            //and the position in the grid
            var pos = transform.position + (Vector3 (x, z, 0) * spacing);
            //Instantiate a clone of the chosen prefab object
            Instantiate(prefab, pos, Quaternion.identity);
        }
    }
}

Ok, well that looks like it. I nice simple tutorial dealing with a few basic concepts of Unity3D. There is obviously a tonne of other stuff to look at, for instance, the physics is very basic at the moment (the cannon balls don’t even bounce) and there are no textures, but I am sure there will be other tutorials.

The final product. Hitting the scales at less than 50kb. Arrow keys to aim, and mouse 1 or left ctrl to shoot.

Powered by WordPress. Theme: Motion by 85ideas.