Sunday, February 23, 2014

My Writing Method v1.85

Why is this version 1.85? Because I'm a neophyte! I love the art of storytelling, but I still have a lot to learn. That doesn't have to stop me from sharing what I've learned! These are steps I rely on when writing. Let's go!
  1. How I Ideate - Ideation is the funnest part for me, I use this method in all of the subsequent steps when I need to get the creative juices going, and so I decided to start with it. So how do I come up with a good idea? I write 25 bad ones. Say I have a scene that involves a hero getting ready to go surf and i need a joke. I go into my word processor; write something like "jokes for scene 2"; push my trusty numbered list icon; think about anything related to the subject of surfing; and write any joke good, bad, or mediocre that comes to my mind without judging it at the moment. In the back of my head, I'll have an idea of which ones are stronger than the other, but I don't worry about that until I've met my joke count of 25. The reason for continuing without looking back is to ignore the bad jokes and the good ones. Ignoring the bad ones prevents me from getting discouraged about myself or frustrated with my writing. Ignoring the good ones prevents me from settling on something when there may be something better if I keep going. Otherwise, it's like going to a restaurant, choosing the first sequential thing on the menu that sounds tasty, and not continuing to read what else the restaurant offers.
  2. Theme - Theme is something I think I'm still trying to fully understand. I tend to think it comes automatically to a story that's interesting. Basically, my understanding of theme is: what is the subject you want to explore? I was tempted to instead explain it as what's the moral to the story? but some of the best stories have no moral, they simply explore ideas and allow us to draw the conclusion. Using one of my favorite movies, Blade Runner, as an example, it explores the moral implications of creating androids, referred to as "replicants," which are almost totally indistinguishable from humans. Blade Runner never really makes a clear judgments on the subject of mankind creating artificial humans... I never walked away from the film thinking "dude, making androids is bad!" even though the replicants are mistreated and multiple humans in the film were attacked by them. Instead, while the film is rightfully critical of slavery, its primarily theme questions what it is that defines our humanity without giving an answer. At least, that's what I took away from it. I wish I could give credit to the person that originally made this point, but some anonymous person pointed out that the androids in the film are more caring for one another than the humans are to their fellow men.

    Comedies seem more forgiving, but they can have themes too! One of my favorite comedies is Anchorman. The film clearly mocks the values of the 1970's, in particular, the struggle of women to be given a fair chance in the workplace. Airplane! is about a guy overcoming his war failures and redeeming himself, even though we don't take his struggle seriously and laugh at his mental anguish. In my series concept, Totally Awesome Dude, I very loosely made the theme the fickleness, foolishness, and irresponsibility of childhood; I thought it'd be fun and fresh to be different from other adult-animated sitcoms with precocious kids such as South Park and The Simpsons. The pilot, Tad Saves the Arcade, maintains that theme with a satire of the cliched "evil businessman trying to shut down our favorite childhood hangout" story. I try to have a theme in mind at least by the time I get to the Treatment phase.

    For a serious dramatic film or short story, I would have the theme in mind in the structure phase; hence, theme is #2 on my list between the those two subjects.
  3. Structure - Different mediums have different act structure and there's even different structures within the same medium (for example, a serialized drama differs from an episodic drama). All stories have a beginning middle end, but the middle can be divided into multiple acts. Made-for-TV movies have many more acts than a feature film because producers want to give viewers a reason to stay tuned in through commercial breaks for 2 hours. A sitcom seem to have 4 acts for one primary storyline, or 3 acts for stories that involve multiple characters (Friends is a good example of the latter). I have not seen more than 3 simultaneous storylines in a sitcom, more often I see two. I notice Friends also tends to finalize one of the less important storylines during the ending credits, which I assume is how they cram so much into one episode.

    Keeping structure because it helps me to find out what I need to fill in the blanks when I get to the treatment phase. So, for example, I'm writing a 22 minute sitcom with 4 acts. Act 1 starts and ends before the first commercial break, Act 2 starts and ends before the second commercial break, act 3 and 4 occur in the last segment of the show. Again, using my example script, Tad Saves the Arcade, as an example (mostly because it's already completed, registered and copyrighted, and been pitched), my structure would be an outline like this:    

    Act 1 - Tad's favorite arcade located within the local pizza place is going to go out of business unless the owner pays the rent.
    [Commercial]
    Act 2 - Tad tries to raise money for the restaurant by doing odd jobs and asking friends for help. He not only fails, but he and his brother accidentally launches a missile at the restaurant.
    [Commercial]
    Act 3 - Tad and friends stop the missile. His friends, thankful of the odd jobs he did earlier, generously grant him the money to help save the restaurant .
    Act 4 - Realizing he can just buy his own arcade machines with all the money he was given, he selfishly lets the pizza shop go out of business.

    Ideation here came from considering funny setup plots as well as "how can I make it more difficult in act 3?" I probably had some other ideas, (I think one with the restaurant owner having a comical heroin overdose), but for whatever reason at the time, I thought the missile plot had the most potential. Missiles are cool. They did it though computer hacking which is also cool. Ideation for Act 4 was deciding whether or not the protagonist will prevail or fail and figuring out how.

    When I first considered structure, I wondered why stories are structured in such a way that the conclusion is shorter than everything else rather than symmetrical.  If I had to guess, I think it's because humans are most interested in the struggle when it comes to storytelling; act 2 and 3 are the the conflict where where we get from the problem to solution. Act 1 is the second longest part because the struggle needs a proper and plausible introduction as to why our protagonist is struggling, and what the stakes are if he fails. Act 4 is the shortest because it terminates the most interesting part, the conflict.
  4. Treatment - A Treatment is different from a series treatment/mini-bible. What I'm referring to is a sheet that plots out each scene and what's to be accomplished. Treatment bridges the gap between structure and writing converging into a map for my characters. If I don't have a solid treatment in mind when I start writing scenes, I tend to write irrelevant scenes or worse, go on a tangent! My characters literally go to locations they're not supposed to and get lost in my imaginary world!

    Ideation here comes in me trying to fill in the acts with scenes and plot point. I write down every idea I have even if it's inconsistent with a previous one (again, maybe I'll find something better if I go a different direction). After I have a huge list of ideas for scenes, I duplicate my act structure list and pull stuff into that new structure list from the scene list to keep things clean without erasing my old ideas.

    This ideation list is fluid; as I come up with one idea, I'll ideate more based on that idea (even though I may never use either). I'm constantly going between acts when I realize something would make a good ending or middle and try to think of a way to set it up in a previous act. The purpose for me is to get my mind firing up its neural pathways. One idea opens up multiple related ideas because of an associated memory or thought, and it just exponentially grows.

    In Act 1, I'm looking at the headings and wondering things like "why is the pizza place shutting down?", "what's the place like?" "how can I show that it's Tad's favorite place"? I also look ahead to act 2 knowing Act 1 has to set it up so I think "why would anyone help Tad?"

    Act 2 has me wondering what would Tad try to save the pizza place. What works, what sets him back and what finally sets up Act 3, things getting worse with the missile. Why does his brother get involved?

    Act 3, I'm wondering how can I resolve these two problems.

    Act 4, Simple: epilogue and conclusion. It's a comedy, so i try to end it on a funny note. This act is so short it's really only one gag over two scenes: Tad receives the money, Tad spends the money.
    1. Act 1 - Tad's favorite arcade is apart of the local pizza place, which he discovers is going to go out of business unless the owner pays the rent to a greedy landlord.
      1. The landlord is in the Illuminati conspiracy and needs the place to perform occult rituals
      2. The landlord's wife is a gold digger and needs new boobs
      3. The tenant is a drug addict and spent all his money on speedballs
      4. Aliens came and attacked the pizza place
      5. Two gangsters from the 1920's traveled through time to rob this one store and create and inter-dimensional protection racket.
      6. The arcade has animtronic animal puppets like Chuck-E-Cheese, but they're really terminator robots in disguise searching for Sarah Conner. 
      7. The arcade has funny games:
        1. A spoof of the ridiculously violent and propagandist game, NARC.
        2. Kid Oedipus 
        3. etc. all the way up to 25.
      8. Jokes about those ball pits at restaurant playgrounds
        1. It's endless and goes to Atlantis
        2. there's a bunch of hypodermic needles in it.
        3. There's a shark in it
        4. etc.
      9. Etc. all the way to 25 whatever...
    2.  Act 2 - Tad tries to raise money for the restaurant by doing odd jobs and asking friends for help. He not only fails, but he and his brother accidentally launches a missile at the restaurant. 
      1. What does Tad try that doesn't work?
        1. Sells candy bars
        2. Trys to get the city to bailout the pizza place
        3. etc. to 25
      2. How does the missile get launched?
        1. They were going to steal the money from the government, but they accidentally hacked the DOD rather than the treasury.
        2. Tad threatens the president to pay for the pizza restaurant or he'll be a terrorist, and the president instead launches a strike on the pizza place.
      3. Why does Johnny get involved with Tad resulting in the missile launch?
        1. Johnny is a genius and conceited. Tad plays to this and eggs Johnny on to hack the computers betting he can't do it.
        2. Johnny just demonstrates how to do it, but Tad actually does it. 
    3. Act 3 - Tad and friends stop the missile. His friends, thankful of the odd jobs he did earlier, generously grant him the money to help save the restaurant. 
      1. How do they stop the missile?
        1. They enlist the help of the resident explosive expert, Ricky to blow it up
        2. They call the pentegon and ask to borrow a jet
        3. They rewind history and recall the missile in reverse. 
        4. etc. to 25
      2. etc. to 25
    4. Act 4 - Realizing he can just buy his own arcade machines with all the money he was given, he selfishly lets the pizza shop go out of business. 
      1. Tad gets the money in a big ceremony. What's the scene like?
        1. Everyone gathers around to witness Tad handing over a giant check to save the shop.
        2. etc. to 25
      2. Tad spends the money on arcade games.
        1. People that helped him are mad that he lied to them about saving the arcade.
        2. The pizza store owner is homeless
        3. etc. to 25
      3. etc. to 25
  5. Writing the "Shit Draft" - An early professional screenwriting mentor of mine explained the "Shit Draft" to me. It was essentially explained to me something like "no matter how good of a writer you are, your first draft is going to to be shit. The best thing you can do is get it out as fast as you can because rewriting is going to be the most tedious step and the purpose of it is to make your draft not be shit." Not wanting to write something that sucks is instinctive to me. Maybe I subconsciously worry someone will see it, or I'll get discouraged that I don't have a natural talent be a writer. I got over this by just forcing myself to complete screenplays and seeing how much the story improves from the first draft. I force myself by just writing out scenes I liked using the outlines in the the finalized (widdled down) version of the treatment outline that I settled on in the previous step. I challenge myself to get it done as fast as I can.

    I also force myself to overwrite. In my treatment ideation phase, I will usually find more than one way to write progress the story. I'll find multiple gags that are really funny in concept, but I will only have room for one. Without seeing these things written out, I can't tell if the flow of the scene or the joke will work. It may be that I have a really funny concept, but I'm unable to execute it. I may have a concept that seems to be not as funny as others, but ends up working really well. The point is, anything that seems worth exploring in my treatment, I write out because I can always cut it later. It would be more difficult for me to add missing parts than cut unnecessary parts. 
  6. Rewriting and Rereading - The most tedious part for me, but also an unavoidable part. It also doesn't help that I'm my most harshest critic. To help me progress through the tedium, I look for the things in the list below, and when I've amassed enough of them, I rewrite. I reread after I rewrite looking for them again, and repeat this process until I'm happy.
    1. Cutting - When I'm looking for scenes to remove for time, I look for scenes that don't advance the story or characters. There's always exceptions to any rule in art, and a major exception here is something memorable or entertaining such as a great gag for a comedy or the cool factor for an action movie.
    2. Pacing - Here, I look to see if the story or characters are constantly progressing and that I'm giving the audience what they want. If I'm writing an action movie, I want to keep the action going as much as possible. If I'm writing a comedy, I want a be a gag to be present in certain intervals (I shoot for at least 1 gag per page). To figure out pace, I read my script and for the most part it's instinct. If there are parts where I feel like I'm slightly losing interest, I figure the audience will have a greater negative reaction since it's not as personal to them. There's also page counts to consider. Again, I don't want to be bound by rules, but industry standards like "Act 1 should be X number of pages" is at least a good rule of thumb. 
    3. Unnatural Dialog - I read dialog aloud. I'm looking to see if it flows off the tongue clearly; if it's easily comprehensible; and to see if it's something the character,with its unique personality would really say. In my first animated pilot I produced, I did the voice acting and want to change multiple lines while recording because they didn't sound right when spoken. I would constantly rewrite it right there in the sound booth. This is an okay approach for something I'm doing on my own, but what if I have to give these lines to an actor? Shouldn't I be happy with the line before I ask someone else to pour their artistic talents (and reputation as an actor) into speaking it? It also isn't an efficient way to work if I'm figuring out a clever way to change the dialog while an audio engineer is being paid to just wait to record it.
    4. Preachy - I'm strongly libertarian and somewhat of a deist. When looking for themes I do pour my politics and philosophy into my work. Like Orwell said, I think all works of art are political. I tend to go overboard and watch to cut back when it's not entertaining.
    5. Inside Gags/Esoteric plots - I have a tendency to want to make really obscure jokes without concern if someone else will get them. For the most part that's okay, unless they're too obscure. My attitude used to be "I'm making this art to express myself, not be popular", which is a good one to have, but it goes too far if I'm making something where I'm the only person on Earth that would understand and appreciate. If I were aiming for that, I would be happy just keeping journals and painting pictures for the rooms in my home.
    6. Saying rather than showing/Saying rather than implying - This is a common rule of thumb. I think it's because audiences likes to infer stuff out on their own. I think it's human nature to enjoy discovering things on our own rather than having them figured out for us. So, I try to avoid filling in more detail than necessary in hopes the audience will say "why did he...? oh yeah I just remembered..." It's also valuable in visual mediums because... They're visual. It conveys the information more vividly and sometimes faster. 
    7. Acting without explanation - This sounds almost converse to the last rule and almost related enough to #3 that they could be put together, but I'd like to make it separate. Recently, I had a tough, but good-hearted character named Max in a scene where he is totally belligerent to another guy, Priest, almost immediately after they just met. Max was also on Priest's property and technically trespassing. It was out of character and didn't make sense for Max. The thought hadn't occurred to me when I wrote it because I was so focused on getting Max and Priest into the next necessary scene where Max is recovering from being beaten by Priest.
    8. Inconsistencies, useless characters, continuity errors, etc. -These are things that take the audience out of your universe and put them back in the theater making them conscious of the fact that they're watching, rather than experiencing. They should be obvious, so I'll be brief. Inconsistencies are plot points that counter another plot point (e.g.: a super rich guy in one scene struggling to make a ends meet in another with no rationale in between). Useless characters are characters that don't add anything to the story, don't interact significantly with the protagonists, or maybe a character that is very similar to another character to the point where they can be combined into one without a problem,. Continuity errors are things like a scene where a family is having dinner one moment, then they're described as having breakfast in the next. 
    9. Proof reading - I try to proofread myself before I ask someone else. It's inconsiderate to have someone else catch a mistake I could've seen if I just read my work. In order not to forget the errors, I print my whole draft and mark it with a colored pen. I learned not to proof read in front of my computer because I will endlessly make tiny trivial adjustments.

      After that, I have my friends and family read my work. It's human nature that my brain will trick me into thinking a word exists or doesn't exist on a page after reading rewriting a script over and over. Having a free third party such as a friend of family member read it helps alleviate this.

      After that, I hire professional proofreaders. I want to present the best possible work I can to studios that review several scripts per week. The last thing I want is to look unprofessional. I consider myself fairly good with grammar, but concede that I would never make it as a professional proofreader, nor do I want that career, so why not just hire one? They're not that expensive either. There are companies online that charge a small fee per word count and I can start and finish the process with them without having to leave my desk. 
    10. Feeback - It's invaluable getting feedback about the actual story from friends, professional script readers, and screenwriters. For the same reason as proof-reading yourself first, get the script as good as you can get it yourself before you ask for someone else's advice. I've only used script readers that have credits or have relevant industry experience. I ask about any parts they didn't get and any parts they thought were boring. I decided to get at least 3 professional readers to look at my stuff if I'm going to try to sell it or put it in a competition. The reason for this is that I've often had one script reader tell me he didn't like a part of a story, while another say it was his absolute favorite part. Obviously, this stuff is subjective and I figure if I get a mixed reaction then I can just rely on my gut at that point.

      Professionals also helped me typographically format my script to conform to industry standards. For example, early in my writing, I was putting "CUT TO:" transitions before every scene and my script was way too long. I learned that this is unnecessary and taking it out reduced the page count significantly. There are many other writing no-no's I learned that I help make me look like less of an amateur in the eyes of producers and agents. 
I'd love any feedback and comments on any improvement or if you want to share your own tips about your own methods. 

Friday, February 21, 2014

C# Stuff and Screenwriting

I neglected to mention a couple of things going on in my last blog.

First, learning C# has been a breeze so far, but I did want to point out a couple of cool things I discovered today while looking at Facebook's unity code. The first is the sealed keyword. This is a keyword that prevents inheritance or overriding. It's like final in Java and AS3. Nothing too special, just thought it was interesting... Come to think of it, it's not interesting, just unusual for me that it's different from "final" and I wanted to note it. The second, actually interesting keyword is #region and #endregion.  These are keywords used in Visual Studio to let the IDE know that you want to make a section of code expand or contract for ease of hiding and showing. It makes it easier to read too. You can title the region with notes!

Also, since I had some downtime waiting for GoDaddy to help me, I worked on a feature-length screenplay for a project I'm tentatively calling Death World. I say tentatively because I really like the name because it sounds like a post-apocalyptic B-Movie. The only problem is that there's a series of books called Death World, which have nothing to do with my feature. I can't talk too much about it because I don't want to give too much away, but I am really happy with the gags and the story flow. I've been devoting too much of this blog so far to programming, so in the coming days I intend to go over the methods of story and joke ideation that I picked up over the years, the obstacles writers have to overcome, and anything else that comes to mind about the art of story telling not just for film, but other mediums.

Thursday, February 20, 2014

Unity Part 6 starring and produced by Bill Cosby.

Actually, I didn't get much input from Bill Cosby on this. I did, however, go through the tutorial on working with the Facebook Unity API from Facebook's Tutorial. It worked perfectly locally, but there were some pitfalls I encountered and mistakes I made along the way.


  1. You'll notice in step 2 of the Configure your app for Facebook Canvas section that Facebook apps require HTTPS hosting of the .unity3d file. I have no experience with security certificates on websites, so I figured this was the time to learn. I thought perhaps there may be a way to do this locally, but I don't have a lot of experience with it and an SSL certificate was only $60 with Godaddy. If anyone has any info on another (free) way to do this, please leave a comment! I tried using self-signed certificates and a local webserver and couldn't get it to work.

    My dedicated server through GoDaddy has a Plesk administrator control installed. I followed GoDaddy's instructions for installing to Plesk 8.x to a tee except that, unlike the direction in Step 11, there was no option to change the domain's certificate from the default one. After much searching, which ,long story short, was difficult since I didn't know what to search for, I discovered that I had to switch the certificate in the IP addresses section in the server configuration. I'm glad I discovered this on my own because GoDaddy would've charged me to get them to help me configure the server even though their instructions seem to be incorrect. Lame!
  2. I notice the Facebook tutorial makes no mention of setting the Site URL setting in the Website section of the app settings. I tried leaving this out just to see if the app would work without it and I couldn't save the settings. So, this field should be the URL for the html file that unity spits out when you build to web player. 
  3. So, in my first build I somehow neglected to put the App Id discussed in Step 6 in and without it, it's impossible to log in. Facebook doesn't really help explain because if you do this, you'll just get an alert error that says "An error occurred. Please try again later." over and over. Be sure to make sure your app Id is right before you upload to your server. For some reason when I uploaded the correct build, it wouldn't show the updated Id. I even deleted the files from the server and reuploaded them and it still showed the 0 default Id. I ended up making a new directory and having Facebook read from it instead. Again, any info as to why my server would serve up an old page (besides caching because I'm pretty sure that wasn't it) please leave a comment. 
That's it! Seemed like a lot I guess because it took me a long time to get 1 and 3 straightened out with my server. My console is working just like in the picture. When I view the app on Facebook, it shows all my friends dialog, status post dialog and so forth. Really neat stuff. My next goal is to send game data from one friend to another. 

Thursday, February 6, 2014

Unity Part V: Return of the NGUI

I wanted to put a scroll pane in my game. Following the tutorials on the NGUI site and manually making empty GameObjects and adding the appropriate scripts didn't work at all! I had no idea what I was doing wrong. I even used the example scroll pane scene and just copied it into my project and it didn't work either! The items in the scroll pane wouldn't render. I couldn't figure it out! I copied all of the settings exactly. Finally, I used the NGUI create panel and it just magically worked. I have no idea what I was doing wrong originally, but I'll make it a point not to add scroll panes without using the menu regardless. My next step? The trade menu. I'm going to be using Facebook to connect players. More on this in my next blog.

Wednesday, February 5, 2014

Unity 2D IV: The Reckoning of the UIs

I tentatively finished up (is that an oxymoron?) my UIs last night. I need to create assets for the other the Trade and Build aspects of the game, so I'm moving on to that today. I created an abstract class for all of my UI menus to extend from that adds some tween scaling on a specified 2D axis.

using UnityEngine;
using System.Collections;

public abstract class AbstractUi : MonoBehaviour {
    private TweenScale SubMenuTween;
    private GameObject LastMenu;
    private Vector3 OriginalScale;
    public enum Axis { X, Y, Z };
    private float TweenDuration = 0.2f;

    protected void Start()
    {
        
    }

    protected void openSubMenu(GameObject subMenu, Axis scaleAxis)
    {
        subMenu.SetActive(true);
        Vector2 finalScale = new Vector3(subMenu.transform.localScale.x, subMenu.transform.localScale.y, 1);
        switch (scaleAxis)
        {
            case Axis.X:
                subMenu.transform.localScale = new Vector3(0, subMenu.transform.localScale.y, subMenu.transform.localScale.z);
                break;
            case Axis.Y:
                subMenu.transform.localScale = new Vector3(subMenu.transform.localScale.x, 0, subMenu.transform.localScale.z);
                break;
            default:
                subMenu.transform.localScale = new Vector3(subMenu.transform.localScale.x, 0, subMenu.transform.localScale.z);
                break;
        }

        SubMenuTween = TweenScale.Begin(subMenu, TweenDuration, new Vector3(finalScale.x, finalScale.y));
        SubMenuTween.method = UITweener.Method.BounceIn;
    }

    protected void closeMenu(GameObject subMenu, float scaleX, float scaleY)
    {
        if (LastMenu == null)   // prevents multiple calls to close window while one is still animating. 
        {
            OriginalScale = new Vector3(subMenu.transform.localScale.x, subMenu.transform.localScale.y, 1);
            TweenScale.Begin(subMenu, TweenDuration, new Vector3(scaleX, scaleY));
            SubMenuTween.eventReceiver = gameObject;
            SubMenuTween.method = UITweener.Method.EaseIn;
            SubMenuTween.callWhenFinished = "onSubMenuTweenClose";
            LastMenu = subMenu;
        }
    }

    public void onSubMenuTweenClose()
    {
        LastMenu.SetActive(false);
        LastMenu.transform.localScale = OriginalScale;
        LastMenu = null;
    }

    

}
using UnityEngine;
using System.Collections;

public class HeadsUpUi : AbstractUi {
    public GameObject MenuUi;
    
    private TweenScale MainMenuTweenScale;
 // Use this for initialization
 void Start () {
        MenuUi.SetActive(false);
        
 }
 
 // Update is called once per frame
 void Update () {
 
 }

    public void OnMenuButtonClick()
    {
        if (!MenuUi.activeSelf)
            openSubMenu(MenuUi, Axis.Y);
        else
            closeMenu(MenuUi, MenuUi.transform.localScale.x, 0);

    }
}
using UnityEngine;
using System.Collections;

public class MenuUi : AbstractUi {

 // Use this for initialization
    public GameObject TravelUi;
    public GameObject BuildUi;
    public GameObject TradeUi;

 void Start () 
    {
        HideSubMenus();
 }

    private void HideSubMenus()
    {
        TravelUi.SetActive(false);
        //BuildUi.SetActive(false);
        //TradeUi.SetActive(false);
        
    }
 
 // Update is called once per frame
 void Update () 
    {
 
 }

    public void OnTravelClick()
    {
        HideSubMenus();
        TravelUi.SetActive(true);
        openSubMenu(TravelUi, Axis.X);
    }

    public void OnBuildClick()
    {
        HideSubMenus();
        //openSubMenu(BuildUi, Axis.X);
    }

    public void OnTradeClick()
    {
        HideSubMenus();
        //openSubMenu(TradeUi, Axis.X);
    }

    public void OnSubMenuItemChosen()
    {
        HideSubMenus();
        gameObject.SetActive(false);
    }

}
Ngui has click events built into buttons, so in my editor, all I had to do was assign things like OnTradeClick to the Trade button, OnBuildClick to the Build button, and so on. The UI needs some aesthetic refinement, but for now it's functional and I need to move on to asset creation to do the rest. Good bye UI programming... I shall return!!!

Monday, February 3, 2014

Unity Part III: The Anchoring

I played around with NGUI some more and I think I'm getting my head wrapped around anchoring. I got my HeadsUp menu looking fly by putting 0 in on the left and right anchor points to the UIRoot and put a higher res image whose width matched my phone's resolution's landscape width. This got it to stretch across the screen without looking lame. The next part was the dropdown menu from the HeadsUp. I did not want that one to scale, I wanted it to align on the right side of a button labeled "Menu" that is on the right side of my HeadsUp menu, as well as a fixed distance down from it. To achieve this, I created a Unified anchor on the MenuUi, set the target of the MenuUi to be the Menu-Button, then set the left and right anchor to the "Target's Right" because I always want MenuUi to be the same distance from the right edge of Menu-Button no mater how it moves or shifts around in its own anchoring system (although the Menu-Button is also a fixed distance from the right edge). The bottom and top portion of the anchor should be inconsequential since I have heights on my menu fixed, but nevertheless, I positioned them relative to the bottom.



At this point, if I adjust the Left number higher or lower it'll scale the MenuUi narrower and wider respectively because its points get closer or further from the right side. If I adjust the Right number higher or lower, it'll scale the MenuUi wider and narrower because it's getting further or closer to the right side. Maybe that's a lousy way to describe it... They're really just points that you're moving, and if you are having difficulty wrapping your head around it, take a look at the yellow lines Unity adds in the image below.

Does that help? I hope so. The blue dots show where the anchors are, the yellow dots are the target's edges. One thing to keep in mind is that changing one anchor without changing its opposite anchor will cause scaling, so I've been adjusting both together by the same amount when I don't want things to scale. To reset to my sprite's dimensions so it's not scaled, I remove the anchor and use the Snap button on the widget's dimensions drop down.

Saturday, February 1, 2014

Unity 2D Part 2

Figured out a solution to making a camera fixed to the edge. Basically, I had my UI root set up wrong. Tasharen, the makers of NGUI, has their website set up differently than I remember, or they changed the site while I was reading the documentation. I noticed more in-depth documentation seemed to be on the forums and I can't seem to find the docs from their site that I was using before. After reading the section on UIRoot, I discovered that UIRoot determines a lot about scaling and resolution adjustment in a game. I set the project's resolution to 1024x600 then set UIRoot's ScalingStyle property to "FixedSizeOnMobiles" with a Maximum and Manual height of 600. After rebuilding and testing on my obnoxiously large Android phone, I got the desired effect. I'm still not sure at this point if this is the correct approach, and I'm reading more on the NGUI documents. I also am not a fan of the stretch look either, but I suspect this is the aspect of android that people warned me about; namely, producers release builds for several resolutions. I can always tell a crappy game in the Android store when graphics are all stretched to hell. I don't want my games to look crappy, so mastering clean UIs will be added to my to-do list. I suspect I'll still have to use stretch, but export multiple resolutions of my source graphics to get the best of both worlds.

While reading the doc, I also found that UIAnchor is deprecated. The original video tutorial on NGUI I watched said to use the UIAnchor class to anchor. Now, NGUI has an anchor option on all of its GameObjects (widgets?).





This blog looks ugly!

I really need to change the layout of this blog. I used Blogger because it was fast to setup and I thought they'd have nicer templates. I'm considering using Wordpress, but I think they nickeled and dimed you from what I remember, particularly on custom domain names. I also found Wordpress a little cumbersome to work with last time I tried, and when I made this blog I didn't want to trick out something I didn't want to initially spend too much time on. I really just had portfolio stuff I needed to show off, but who in their right mind would want to hire someone in my line of work that has an ugly blog? And guess what? Man, This blog is ugly. Thanks Dan, for pointing it out. I needed the encouragement... Or is it the discouragement?

Unity 2D!

Excited to be working with Unity 4 with its new 2D capabilities built in. In the past, I used 3rd party plugins with Unity to build 2D games, but they always felt clunky. To get better at Unity, I took a challenge upon myself to make an simplified versions of one of my favorite mobile games, Happy Street. My goals are to:

  1. Build or find a swipe camera class to allow the player to swipe the camera along the x-axis./li>
  2. Build or find a class allowing pinch zoom in and out.
  3. Build a repeatable, non-animated terrain for 4 locations: City, Forest, Beach, and Mines
  4. Have an animated sprite for a character that randomly walks left and right, and has idle frames for both directions called at random.
  5. Have a UI that allows players to change locations and build.
  6. Have resources to collect in forest, beach, and mine locations. 
  7. Allow players to build buildings in city based on the amount of resources they have. 
  8. Constrain swipe and zoom. 
  9. Connect the game to Facebook's Unity API.
  10. Have players trade resources through the Facebook api. 
Task #1 - Scrolling camera gesture
Initially, I created my own class that allowed for swiping since it was such a simple task. The class below is to be placed directly on my main camera...

using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour 
{

    public float SwipeSpeed = 0.1f;

 void Start () 
        {
           
 }
 
 // Update is called once per frame
 void Update () {

        switch (Input.touchCount)// number of fingers on the screen.
        {
            case 0:
                break;
            case 1:
                Scroll();
                break;
            case 2:
                Zoom();
                break;            
        }
        
    }

    private void Zoom()
    {
        // Todo
    }
    
    private void Scroll()
    {
        if (Input.GetTouch(0).phase == TouchPhase.Moved) // if the finger has moved since the last update
        {
            Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition; // just to make it neater, I set a variable.
            // in the line below, I move this GameObject (the camera) in the opposite direction of the swipe for a swipe scroll effect.
            transform.Translate(-touchDeltaPosition.x * SwipeSpeed, 0, 0);    
        }
    }
}
This worked well except that I don't have the nice scrolling tween upon release of a fast swipe like Happy Street does. I decide to come back to that later recalling that NGUI had a built-in camera scroll class that may be promising. If it meets my criteria, I'll use it, if not, adding a tween should be simple; I suspect that could be done using the Mathf.SmoothDamp function.

Task #2 - Zooming
Let's get that Zoom function working...
using UnityEngine;
using System.Collections;

public class CameraController : MonoBehaviour {
    public bool isActive;
    public float SwipeSpeed = 0.1f;
    public float ZoomSpeed = 0.001f;
    private float _DeltaZoomDistance = 0;
    public GameObject groundController;
 void Start () {
           isActive = true;
 }

 void Update () {

           switch (Input.touchCount)
            {
                case 0:
                    ResetTouch();
                    break;
            case 1:
                    Scroll();
                    break;
            case 2:
                    Zoom();
                    break;            
            }
        }

    private void ResetTouch()
    {
        _DeltaZoomDistance = 0; // resets distance to prevent 
    }

    private void Zoom()
    {
        Vector2 touch0, touch1;
        float distance;
        touch0 = Input.GetTouch(0).position;
        touch1 = Input.GetTouch(1).position;
        distance = Vector2.Distance(touch0, touch1); // How far apart are the fingers?
        float zTranslation = distance - _DeltaZoomDistance; 
        // zTranslation stores the new position of the z axis based on whether or not the fingers got further apart or closer together.
        // I do this using _DeltaZoomDistance which keeps track of the previous distance zoomed to ensure it only moves upon change in the touch distance.
        // Otherwise, I suspect it would immediately move when I first touch and zTranslation would be an incorrect value anyway.
        if (_DeltaZoomDistance != 0)
            transform.Translate(0, 0, zTranslation * ZoomSpeed);
        _DeltaZoomDistance = distance; // set the zoom distance 
    }
    
    private void Scroll()
    {
        if (Input.GetTouch(0).phase == TouchPhase.Moved)
        {
            Vector2 touchDeltaPosition = Input.GetTouch(0).deltaPosition;
            transform.Translate(-touchDeltaPosition.x * SwipeSpeed, 0, 0);
        }
    }
}
I decide to wait to constrain the camera until all my assets are in so I can see how much I need to constrain it, and because I'm not quite sure how exactly I want to approach that yet anyway.

Item #3 repeatable non-animated terrain.
I decide to use the same method I've used for 3D games which is to basically make prefabs and place them next to each other. The difference is that now I have to learn to use Unity's new Sprite GameObject, which is pretty simple once you get the hang of it. In your inspector, simply switch your texture asset's "Texture Type" to sprite. Create a new sprite in the GameObject menu, then assign your sprite texture to it. To save a step, if you have your sprite texture selected when you create a new Sprite GameObject, it'll put the texture on it for you. I ran into an issue where the material on the Sprite GameObject was not set the first time I used it. I'm not sure why that happened, but if it ever happens again, the correct default material is "Sprites-Default".
I notice the ground in Happy Street's terrain is not exactly 2D. There is some perspective on the nearest terrain that is noticeable upon camera swipe. Everything else in the game appears to be 2D, So I decide the best way to copy their effect is to rotate the ground portion of the terrain along the x axis to give it some slight perspective.
 
To make the terrain repeatable, I put a box collider around the terrain matching its dimensions, then I put the following script on an empty GameObject named "GroundController" and set the "Chunk Prefab" property to my terrain prefab.
using UnityEngine;
using System.Collections;

public class GroundController : MonoBehaviour {
    public int chunckLength = 10;
    public GameObject ChunkPrefab;
    private GameObject[] Chunks;
 void Start () {
            addChunks();
 }

    private void addChunks()
    {
        // I keep my initializations out of my for loop to prevent memory from being reallocated with each iteration
        int i = 0;
        float nextXPosition = 0;
        Vector3 newPosition;
        GameObject chunk;
        for (i = 0; i < chunckLength; i++)
        {
            chunk = Instantiate(ChunkPrefab) as GameObject;
            newPosition = new Vector3(nextXPosition, chunk.transform.position.y, chunk.transform.position.z); 
            chunk.transform.position = newPosition;
            nextXPosition += chunk.GetComponentInChildren().size.x;
        }
    }

    void Update()
    {
       // left this function in because I may need it later.
    }
}


Item #4 - UI
Item for is where I left off. I am new to using NGUI, which seems to be favored by the Unity programmers I've talked to. That said, I like it a lot.
I set up my tree as so:
 
HeadsUp, MenuUi and TravelUi are empty game objects. The sprites of the background and the buttons are actually on the children of those GameObjects to keep them organized. I use NGUI's anchor script to anchor the buttons to each menu, and each sub menu to the HeadsUp menu. Anchoring allows one to link the positioning of one 2D object relative to another. This way if the positioning changes on the object the relative position changes to on the subservient object. In my case, I anchor the MenuUi to the HeadsUpUi, and make TravelUi a sub menu of the MenuUi, so I anchor it to that. I offset everything so it looks good in the Game preview panel. After I create the Menus, test an APK on my obnoxiously large Android phone. I notice that the menu is not bannered across the top of the screen like it is in my Game panel. I can't anchor it to the camera I don't think because the camera doesn't have dimension. I anchor it to NGUI's root UI instead. Initially, when I first worked with the UIAnchor script, I thought the Container property always had to be set. After working with it for much too long, I came to the conclusion that if one does not set a property on the Container property of the UIAnchor script, it defaults to the camera. This conclusion turns out to be wrong. I suspect it may be an issue with various resolutions on Android phones if it's not something I'm doing wrong with UIAnchor.