Tuesday, July 22, 2014

Unity 3D and Phidgets: Basic Setup

For those of you out there interested in using Unity for physical computing, I'd like to let you in on a fantastic hardware company: Phidgets. They make everything from LCD displays to motor controllers to I/O boards and more. I've used nearly every type of product they make in products that total thousands of unit shipped, and I've found them to be simple, robust, reliable, and an all-around joy to work with.

This basic setup will get you working with any devices that Phidgets make. There are a few little gotchas in the setup, but once you get to the point where Unity recognizes them, they're quite simple to work with. This article will deal with the universal setup for any Phidgets device, and then I'm going to work up a series on the specifics of each type of device.

We're going to assume some working knowledge of Unity (navigating the various panes, creating objects, etc.) and C#, so there won't be as much explanation on basic topics as usual. If you're not at that point yet, I recommend you check out the Unity Basics, and the BurgZerg Arcade Hack & Slash Tutorial. BurgZerg's is my favorite for going from basic Unity knowledge to working game, learning some very good C# along the way.

Here are the steps we're going to take to get Phidgets working in Unity on a Windows machine:

1. Download and run the Phidgets Installer. This will be required for basic communication with Phidgets devices. Make sure that you get the correct installer for your OS (32-bit or 64-bit). If you're not sure which one you have, you can right-click on Computer from the Start Menu, select "Properties", and look under the System heading. Under "System type", you will see that you have either a 32-bit or 64-bit operating system. If you're going to develop on 64-bit Windows but your production machines will be 32-bit, you'll want the 64-bit installer on your development machine and the 32-bit installer for your production machines.


2. Plug in your device and make sure it is recognized. Whichever Phidget you have, go ahead and connect it, then open the Phidget Control Panel. Do so by opening the taskbar in the lower-right-hand corner of the screen, and double-clicking the little "Ph" icon.


In the Control Panel, you should see an entry for each attached device, as well as the serial and version numbers. If you double-click on a device entry, it will open the test program for that device. Once you're satisfied that your device is recognized and functional, you can close the Control Panel and move on.


3. If you haven't already, create a new Unity project.

4. Copy the Phidget21.NET.dll file to your Assets folder. For the sake of organization, I prefer to make a folder under Assets called "DLLs", and move it to there. If you installed to the default directory, this DLL will be found in either "C:\Program Files\Phidgets" or "C:\Program Files(x86)\Phidgets".

5. Create a C# script to control your Phidgets device. It's really up to you how you do this; I prefer to create a separate script for each type of device. At the top your script, you're going to need to add the following lines of code:

using Phidgets;
using Phidgets.Events;


These lines will allow you to talk to your Phidgets devices and utilize their event system.

That's pretty much it! Now, I have had some issues getting Phidgets to work initially, although once they work, they've always continued to work. Occasionally, I've had to restart after adding the DLL to the Assets folder before any communication would take place. Also, in older versions of Unity, I had to change from the .NET 2.0 subset to .NET 2.0 in Player Settings, but lately I haven't had to. Finally, I've read that some folks needed to add a reference to the Phidgets DLL in MonoDevelop, but personally, I've never had to.

So you can use this method to talk to any Phidgets devices. I'll be tackling some of them in a future series, and this will serve as the basis for all of those tutorials. In the meantime, head over to their site and get your imagination working!

Monday, July 21, 2014

Unity 3D: How to Create a Simple Pop-Up Window with NGUI

Anyone who's read my tutorials knows that I'm a big fan of NGUI. I feel it's the best third-party GUI tool for Unity, but there is a little bit of a learning curve, which is why I've worked out a series of articles on some of the simplest ways to implement oft-needed objects in NGUI. Today, we're going to make a pop-up window.

If you don't already have NGUI, go grab it now (full or free). Also, if you aren't already comfortable with NGUI buttons, you can check out my tutorial here.

Since I just posted an article on linking to a Google Play app to rate it, we'll create a window that does exactly that. Our window will simply ask if the player would like to rate our app, and give them the option to go on the Play Store or close the window. We're also going to make a button that pops up the window, but that is strictly for demonstration.

First, we need to get our GUI set up in the scene. In the toolbar, go to NGUI > Create > 2D UI. This will get us ready to use the NGUI objects.


In your hierarchy, you now have an object called "UI Root." This contains all the base components needed to render the UI, and will be the parent of all of our NGUI objects.

For the window itself, we'll use NGUI's example background object, called "Control - Background". You can search for this in the Project pane, or get it directly at "NGUI/Example/Atlases/Wooden/Control - Background.prefab". Drag it into your scene, right on top of  "UI Root > Camera", making it a child of the Camera object. Your hierarchy will look like this:


This is all we really need for the window itself. You can change the size by clicking the "Control - Background" object and altering "Widget > Size" in the Inspector. You can also select a different sprite by clicking the "Sprite" button in the UISprite properties under the Inspector. If you want a completely different set of images to choose from, select a different atlas by clicking the Atlas button in the UISprite properties under the Inspector.


So we have a basic window, but now we need to add some text. In your toolbar, select NGUI > Create Label.


You want to drag the "Label" object that is created in you scene on to the "Control - Background" object to make it a child of that object, if it isn't already. This way, when you move/hide the pop-up window, the text will move along with it. Also, pay attention to the "Depth" property. You want to make sure the label you just created has a larger Depth number than your window, or your text will be behind it.

Change your label to read what you'd like by changing the "Text" property under the UILabel script in the Inspector. I've gone with "Please rate our app!" Again, we can customize this text in a number of ways, including changing the "Size" property, or selecting a different font by clicking the "Font" button, all under the UILabel script in the Inspector. There are lots of ways to change text; if you're interested, you can check them out here.


So now we have our window and text; next, we need buttons to either rate the app or close the window. Find the "Control - Simple Button" prefab in the Project pane, and drag two of them into your scene, right on top of "Control - Background" to make them both children of the pop-up window, just like we did for the label. Set your depth and position them where you want. Change their text by altering the "Text" property of the Label under each one. Also, give them unique names by selecting each "Control - Simple Button" object and renaming it (either press F2 or right-click and select "Rename"). Here, I've named them separately ("Rate Button" and "Close Button"), and changed their label text to "Sure!" and "No thanks!" We've also played around with the colors a bit.


Now that our window is ready, we're going to use a simple bit of code to open and close it. Keep in mind there are plenty of ways to handle this, but I'm working from what I believe is the simplest point. You can build on this or alter as needed.

First, let's add another button to the scene that will just show and hide the window. Stick this button somewhere, then create a C# script named "TogglePopUp". Double-click on the script to edit it, and paste this into it:

using UnityEngine;
using System.Collections;

public class TogglePopUp : MonoBehaviour
{
    public GameObject popUpWindow;

    void OnClick ()
    {
        if (popUpWindow)
        {
            if (popUpWindow.activeSelf)
            {
                popUpWindow.SetActive (false);
            }
            else
            {
                popUpWindow.SetActive (true);
            }
        }
    }
}


This is a very simple script, but let's go through it quickly. First, we declare a public GameObject. Once we attach this to our button, we'll be able to assign a GameObject to it in the Inspector. This is the object we want to show or hide. Now, we use the OnClick () method to respond to a button press -- this is a default NGUI behavior. Inside OnClick (), we first check to see if the the popUpWindow GameObject has been assigned, because if we try to set anything on that GameObject without assigning it, we'll get an error. The inner if () statement is where all the real logic happens. If the object is active, make it inactive. If it is inactive, make it active.

So drag this script on to the button you're using to toggle the window. Then drag the pop-up window object (in my project it's still called "Control - Background") onto the "Pop Up Window" field under the "Toggle Pop Up" script in the Inspector.






Press Play to run your game. When you click your toggle button, the window should disappear and reappear. This is the basis for your pop-up: your window will be present but inactive when the scene starts. When you need to show it, set it to active. When you need to hide it, set it to inactive again.

Now, combining this tutorial with the button tutorial and the rating tutorial, you can see how to easily build a pop-up window to ask the player to rate your app. Once the player has reached the point where you want to ask for a rating (for instance, after a particular level is finished), you can pop this window up. One button will close the window again, and the other will open your app's store page.

Unity 3D: How to Let a User Rate Your Google Play Store App

Ratings in the Google Play Store can make or break your app. It's critical to allow users to easily provide feedback. Since it is so easy to open a link to your game's page on Google Play, we're going to go a little further and talk about best practices and provide some implementation suggestions.

If you just want the code, here it is:

Application.OpenURL("market://details?id=com.RnRVertigo/");

Now, you'll want to replace my package name (I can do some promotion on my own blog, right?) with yours. So where I'm using "com.RnRVertigo", you would enter your full package name, which can be found in your manifest file or in the Developer Console, at the top of the page, next to your game's name. It will generally have a format like "com.gameName" or "com.companyName.gameName".

All our code is doing is opening a URL to our Google Play Store page. The user can rate it from there. Notice that we're not using the typical "http:\\" or "https:\\" prefix; we're using "market:\\". On Android, this will open this link directly in Google Play. We could also do this:

Application.OpenURL("http://play.google.com/store/apps/details?id=com.RnRVertigo");

This will simply open the Google Play link in a web page, and if they haven't set a default to handle Google Play requests, prompt the user if they'd like to use the browser or the Google Play app. You may have use for this, but I generally avoid it because it potentially adds another step to the user's process, and I always shoot for simplicity. If you'd like some more details on Google's product linking policy, check out their page.

Before we go any further, you should know that Google Play explicitly prohibits us from attempting to manipulate our ratings with incentives, blackmail, etc. From the Google Play Developer Program Policies, pay specific attention to this line:

"Developers must not attempt to change the placement of any Product in the Store, or manipulate any product ratings or reviews by unauthorized means such as fraudulent installs, paid or fake reviews or ratings, or by offering incentives to rate products. "

So, it's perfectly fine to ask, "Would you like to rate this app?" or "Please rate us 5 stars!" while it is against policy to say something like "Rate us 5 stars for a free gem!" or "Give us 5 stars to continue playing!" Yes, I know you've seen very popular games that do it. Just don't. While it's highly unlikely that your app would be pulled from the store, it becomes far less likely that Google would be willing to feature your app or involve you in potentially valuable promotions. Also, it's very off-putting for users, and keeping them happy is the goal, right?

There are an infinite number of ways to implement this, but in general, we should try to be as unobtrusive and respectful of the player as possible. Of course we should stick to the Google Play Developer Program Policies, but here are some guidelines I also follow for myself:

Let the user play for a while before rating. This is kind of obvious, but why should they rate a game they've barely played? Pick a point in the game (i.e., after a particular level or number of rounds) where you feel the user has played enough to form an opinion on the game. I avoid going time-based (i.e., two days after installation) because plenty of people will install a game and not play it for days, weeks, or even months.

Make declining to rate just as simple as choosing to rate. A simple window that says something like "Please rate our app!" with buttons reading "Sure!" and "No thanks!" is sufficient. Keep it simple and uncluttered, and remember to close the pop-up when they click either button -- when they come back to your app, you don't want them to have to close it manually. Adding options like "Don't ask again" is one of those small barriers to play that can add up and turn people off to a game, which brings me to my last point ...

Only ask once. If they went on to rate it, we don't need to ask again. If they don't want to rate it now, they probably don't ever want to. Nagging players to rate your app is a great way to get them to give you a low rating just because you're irritating them.

The bottom line is, do what is best for the player and you can't go wrong!

Friday, July 18, 2014

Unity3D: How to Post to Facebook from your Unity Game

We've shown you a simple way to post to Twitter from within your game; today, we're going to tackle a simple way to post to Facebook. The general idea is the same, but there's a little more setup involved. I'm going to supply a template that will work out of the box, and we'll talk about the specifics afterwards.

Before you get cracking in your code, you're going to need to create a Facebook app to handle sharing from your game. Start by going here to create your app.

Once your app is ready, we're going to use it to publish to Facebook. Much like Twitter, we're going to use Application.OpenURL to send the request to Facebook and let them make the magic happen.

If you've read my other posts, you'll know that I'm a big fan of using NGUI for buttons and the like. If you're not using it, I've written a very simple post on getting started with it. With NGUI, just call the ShareToFacebook () method in the OnClick () method of the button of your choice, passing in the proper parameters.

You may have stumbled across similar code, but nearly all of the examples I've found were forming the URL improperly. Here's what I have, and it works wonderfully:

private const string FACEBOOK_APP_ID = "123456789000";
private const string FACEBOOK_URL = "http://www.facebook.com/dialog/feed";
 

void ShareToFacebook (string linkParameter, string nameParameter, string captionParameter, string descriptionParameter, string pictureParameter, string redirectParameter)
{
Application.OpenURL (FACEBOOK_URL + "?app_id=" + FACEBOOK_APP_ID +
"&link=" + WWW.EscapeURL(linkParameter) +
"&name=" + WWW.EscapeURL(nameParameter) +
"&caption=" + WWW.EscapeURL(captionParameter) + 
"&description=" + WWW.EscapeURL(descriptionParameter) + 
"&picture=" + WWW.EscapeURL(pictureParameter) + 
"&redirect_uri=" + WWW.EscapeURL(redirectParameter));
}

If you've followed our Twitter post, you can see that there is a little more to this. The FACEBOOK_APP_ID comes from the app that you built (I've used a fake one here, so remember to replace it with yours). The FACEBOOK_URL is the URL used for posting to the feed. After that, we get to the meat and potatoes of customizing our content.

linkParameter is the link that will be posted to the wall. For example, you could link to your game's website or download page.

nameParameter is the title of your post. You probably want to briefly describe what it is you're posting (i.e., "I'm playing Game XYZ!"). The name will be a link to the URL described by linkParameter.

captionParameter is the caption of your post. This appears in small type right below the title of your post. It may be a good idea here to give a bit more detail on what you're posting (for example, "New high score!"). 

descriptionParameter is the body of the message. Here, you can give the bulk of your message, such as the score you attained, an achievement you unlocked, etc. 

pictureParameter is a link to a picture you'd like to include in your post. Keep in mind that pictures must be at least 200px x 200px.

Finally, redirectURIParameter is the page the user will be redirected to after publishing their message. This is the parameter that is likeliest to cause you a headache. If you want to go the no-hassle route, just link to http://www.facebook.com/.

Improperly forming your URL or trying to redirect to a domain that is not assigned to your Facebook app are almost always the cause of error 100 and error 191. If you experience either of these, ensure that your URL is being formed correctly by comparing it to the URL redirection example on this page.

If you want to redirect to a page that is outside of Facebook's domain, you'll need to take a couple of extra steps. First, go to your app's page, and select "Settings" from the menu on the left. Click the "Add Platform" button, and select "Website". Under "Site URL", enter the page you want to associate with your app. Now, under "App Domains", enter the domain that page belongs to. So, if you added your Site URL as "www.example.com/index.html", you'll want to enter "www.example.com" under App Domains. Now, your redirect should work as intended.

If you'd like to go more in-depth, you can view the Feed Dialog documentation here. Keep in mind that you can use the Share Dialog, as the Feed Dialog is deprecated, but we're going for simplicity here, and I think this is the quickest and easiest way to get Facebook sharing going.

Tuesday, February 11, 2014

Unity 3D: Easy Draggable Windows with NGUI

If you want to make a panel or window that can be moved around when by the user via their mouse, NGUI makes it extremely simple. We're going to do it in a matter of minutes, and without writing a single line of code to boot!

Let's say you've got a nifty menu window that you want your user to be able to move around. I've used the SciFi example atlases that NGUI comes with to create a simple little window made up of some sprites and a label. It doesn't matter exactly what you use.


I have made all of these elements children of a panel (NGUI > Create > Panel), so that when the panel moves, it all moves.


After we make the window that we want to drag around, we need to add a Collider to the element the user needs to click to drag the menu around. In our example, we want to be able to drag the title bar (the background to the word "MENU") and have the rest of the elements follow. In the example above, it's the "Title Bar" sprite. Add a Box Collider to that element, and resize it so that it's the same size as the element you want the user to click to drag.


Now, there's just one script left to add. It's found in your Project view under "NGUI > Scripts > Interaction." It's called "UIDragObject". Drag that script right on to the object you added your collider to. Click on that object, and scroll down to the settings for the "UIDrag Object (Script)" component in the Inspector.

Notice that the "Target" parameter is not set. We need to tell the script what object we want to move when the user drags their mouse around. In our case, we're going to drag the "Panel" object -- the parent of all the menu objects -- from the Hierarchy to this parameter.


That's all there is to it. Run your scene, grab the title bar, and drag your menu around!

Monday, February 3, 2014

Unity 3D: How to Post to Twitter from your Unity Game

Nobody can deny the power of social media in building an audience for your game. I'm going to be writing a few posts detailing the simplest ways I know of for sharing your game via some popular social media sites; today, I'm going to focus on Twitter.

I create almost all of my buttons with NGUI. If you're not using it, I've written a very simple post on getting started with it. If you're using NGUI, you'll call the ShareToTwitter () method in the OnClick () method of the button of your choice, passing in the text you'd like to share. Regardless, you just need to call this method with the text that you'd like to share, hashtags and all.

private const string TWITTER_ADDRESS = "http://twitter.com/intent/tweet";
private const string TWEET_LANGUAGE = "en";

void ShareToTwitter (string textToDisplay)
{
Application.OpenURL(TWITTER_ADDRESS +
            "?text=" + WWW.EscapeURL(textToDisplay) +
            "&lang=" + WWW.EscapeURL(TWEET_LANGUAGE));
}

So what are we doing here? Well, we're opening a URL, which in this case is the URL that Twitter uses to allow us to post to our account. On a PC, this will open the browser and attempt to post Twitter the textToDisplay parameter. On mobile devices, this will open the Twitter app or the browser, depending on what the user has.

You can build up the textToDisplay parameter however you like; just remember the 140-character limit. Include hashtags, a link, your score, whatever.

Thursday, January 23, 2014

Unity 3D: Awwww, Snap!

These aren't brand new techniques, but they weren't in Unity from the outset, so even some veterans seem to be unfamiliar with them. Unity is able to snap objects to a custom grid, or to one another.

To snap to a custom grid, you can first set up the size of the grid by going to "Edit > Snap Settings." Let's say I have a prefab at a size of (0.5f, 1f, 0.5f), and I want to snap a bunch of instances together on the X and Z axes. I can just set the "Move X" and "Move Y" values to 0.5, and I know that every snap step is exactly one object unit in either direction.

To actually snap, just grab an object and move it while holding Ctrl in Windows or Cmd on Mac. Now, the object will move by the amount you designated in "Snap Settings."

Snapping meshes together is even simpler: just hold Shift + Ctrl or Shift + Cmd and drag an object around by its center. Note that the objects being snapped together both need to have colliders.

Finally, you can snap objects together by vertices. This one's a little more involved but it's great for attaching dissimilar, oddly-shaped or -sized objects. Taken directly from Unity's "Positioning GameObjects" page:

Vertex Snapping
  • Select the mesh you want to manipulate and make sure the Transform Tool is active.
  • Press and hold the V key to activate the vertex snapping mode.
  • Move your cursor over the vertex on your mesh that you want to use as the pivot point.
  • Hold down the left button once your cursor is over the desired vertex and drag your mesh next to any other vertex on another mesh.
  • Release your mouse button and the V key when you are happy with the results.
  • Shift-V acts as a toggle of this functionality.
  • You can snap vertex to vertex, vertex to surface and pivot to vertex.