Showing posts with label unity. Show all posts
Showing posts with label unity. Show all posts

Saturday, March 15, 2014

Unity Part VIII: Unity and Parse.com Part 2: The Reckoning

I'm having a lot of difficulty understanding multi-threading in parse.com. I've posted question to Parse's forums and I'll be updating my blog when I get it all figured out.

The main issue I'm having is continuing the execute code after calling an asynchronous command to parse and getting a response. I get this error:

InternalGetGameObject can only be called from the main thread. 
Constructors and field initializers will be executed from the loading thread when loading a scene. 
Don't use this function in the constructor or field initializers, instead move initialization code to the Awake or Start function.

It occurs from doing something that, I think, should be very basic: Hiding my login form after a successful login. Here's the code:

private void ValidLogin(string un, string pw, LoginCallback loginCallback)
{
    Task task = ParseUser.LogInAsync(un, pw).ContinueWith(t =>
    {
        if (t.IsFaulted || t.IsCanceled)
        {
            _LoginErrorMessage = t.Exception.Message;
        }
        Test();
    });
}

private void Test()
{
    if (_LoginErrorMessage == "")
    {
        SetVarsFromParseUser();
        SaveLocalUserData();
        RemoveLoginForm(); // This function causes an error
    }
    else
    {
        PrintFormErrorMessage(_LoginErrorMessage);
    }
}

public void RemoveLoginForm()
{

    LoginUserMenuInstance.gameObject.SetActive(false);
}

Removing "RemoveLoginForm" negates the error, but then my login form would be on the screen... forever!!!

I suspect the error is from trying to execute code for the main thread in a subthread, but I have no idea how to achieve what I want to do otherwise.

This week I also got local save data in. I am basically saving to XML at the moment, but this is insecure, so I'd like to find a better way. At the moment, the user could simply edit the XML to cheat. Nevertheless, I've included my method below.


private void SaveXml()
{
    GameData.username = Username;
    GameData.password = Utility.Md5Sum(Password);   // Custom function for converting to MD5
    XmlSerializer serializer = new XmlSerializer(typeof(GameData));
    FileStream stream = new FileStream(_DataFile, FileMode.Create);
    serializer.Serialize(stream, GameData);
    stream.Close();
}

private bool OpenXml()
{
    Xml = new XmlDocument();
    XmlSerializer serializer = new XmlSerializer(typeof(GameData));
    FileStream stream = new FileStream(_DataFile, FileMode.Open);
    GameData = serializer.Deserialize(stream) as GameData;
    stream.Close();
    return true; // for later in case I decide to do error checking.
}
As you can see, the code requires a custom class for handling XML and I've named mine GameData. I've included it so you can see how it works.
using System.Xml;
using System.Xml.Serialization;
 
[XmlRoot("GameData")]
public class GameData
{
    public string username;
    public string password;
    public int lastLocation;
    public uint goldCoinCount;
    public uint productoTronCount;
    public uint cityLandLotCount;
    public uint beachLandLotCount;
    public uint forestLandLotCount;
    public uint mineLandLotCount;
    public uint storage;    
}
For more info on saving and loading XML for your Unity game, check out this article on Unity's wiki.

Sunday, March 2, 2014

Unity and Parse.com

In my last Unity post, I discussed working with the Facebook API. My thought at the time was that it would be a good way to exchange data between users. While it may be possible to do that with the Facebook API, I don't believe this is its primary purpose and anyway, the Facebook tutorials recommended using Parse.com. So I looked at parse.com and I love it. Here's their description:

The Parse platform provides a complete backend solution for your mobile application. Our goal is to totally eliminate the need for writing server code or maintaining servers. If you're familiar with web frameworks like ASP.NET MVC we've taken many of the same principles and applied them to our platform. In particular, our SDK is ready to use out of the box with minimal configuration on your part. Parse's Unity SDK makes heavy use of a subset of the Task-based Asynchronous Pattern so that your apps remain responsive...

It's very simple to setup and it's free! Well, free to develop on... If you get to a point where you need to hold a bunch of data, then they charge you. It's not going to solve real-time data syncing, instead it offers task based data retrieval. A request needs to be sent with each write and query to the database.

It's so simple that I created registration and login forms for my game after a few hours of coding. My game will be using its online database for backing player's save game as well as facilitate trades between users. I say backup the player's data because the data will only update upon downloading an existing game to a new device, closing the game, and after trade between users. My thought is it'll cut down on traffic. Locally, I'm using XML to save the player's data using C#'s XmlDocument class, which is also really simple to use. My next goal with Parse is to get a many-to-many relationship stored so that players can conduct trades and a one to many relationship for players' inventory. Parse has its own query structure that I haven't worked with yet, but seems pretty straight forward.

Before I get to that, I have to get the rest of the game mechanics worked out. I have resource collection functionality I need to design and implement. I decided on three locations where one can collect resources: Beach, Forest, and Mine (not unlike Happy Street). Each of the three will have three resources a user can collect. A fourth location, City, will be where a player can put those resources to use either by purchasing buildings or crafting new items from simpler ones.

Anyway, lots of stuff yet to be done with regard to this multiplayer aspect, but I wanted to share my experience and give my recommendation for Parse. I did also get through all of the Facebook Unity tutorials and they were pretty straightforward as well. I intended to get back into Facebook to implement promotional features, but as more as a finishing touch.

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?).





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.