Linux Format

Unity for Linux

Jonni Bidwell dabbles with the experiment­al Linux editor for Unity, discoverin­g physics, C# and little spinning charms.

-

Jonni Bidwell dreams of becoming a game developer and escaping to the green pastures of New Zealand, then being entrapped as a wage slave again. Swings and roundabout­s.

The Unity game engine has featured a Linux runtime since version 4, which was released in 2012. Allowing developers to export to Linux without any extra effort has enabled a raft of great titles find their way to our penguin-powered desktops: Cities: Skylines, Kerbal SpaceP rogram and Pillars of Eternity and the list goes on. Until recently, those wanting to actually make Unity games on – as opposed to for – Linux were forced to run the editor through Wine. We’ve showed how to do this in past issues [see Code Academy, p88 LXF199] and unlike many of our other Wine experience­s found it to work pretty well. However, it’s nice to not have to rely on Wine, and now thanks to the recently released Linux version of the Unity Editor. To get it installed see the box opposite, be aware that this software is ‘experiment­al’ and should be treated as such. We ran into the odd glitch, mostly connected to dragging and dropping components. You may run into worse, in which case you’d be advised to recourse to running the Windows version through Wine.

At this point it’s not clear how much attention the Linux editor will receive. Thanks to a passionate and vocal community, developmen­t of a Linux editor was one of Unity’s most requested features. A great deal of work went into creating it, and it would be a shame to see it abandoned. Unity’s Linux runtime was also introduced as an experiment­al feature, and that has turned out remarkably well, as evidenced by the impressive numbers of Unity games being developed for and played by Linux users. Hopefully the burden of maintainin­g the Linux editor will be similarly justified by developer interest. For this article we’re going to follow the Roll A Ball tutorial which you can watch online at http://bit.ly/RollABall and credit for the material goes entirely to Unity’s Adam Buckner.

When you first start Unity ( unity-editor from the command line if you can’t find it elsewhere), you will be prompted to sign up for a free account. This seems to be mandatory, use a throwaway email if you’re concerned. You’ll then be prompted for a project name and location. Feel free to watch the friendly ‘Getting started’ video first, then let’s call our project LXFRoll and store it in the suggested Documents/directory. Unity allows additional asset packages to be imported at this stage, but there’s also precurated collection­s for 2D and 3D games, we’ll use the 3D one, which is highlighte­d by default. Initially things may seem daunting, but don’t feel intimidate­d, Unity is incredibly powerful. Also note that the default Linux layout will appear different to many of the tutorial videos out there – don’t worry, all the features are there, and you can rearrange things from the Layout drop-down in the top-right.

Initially our project consists of two objects, a Main Camera and a Directiona­l Light, which you can see in the Hierarchy tab in the top-left. These are fairly fundamenta­l to any project: without a camera there would be no point of observatio­n and without a light everything would be dark. You can pan around the central Scene View using the right mouse button and zoom in using the mouse wheel. Clicking on the camera in the Scene View (or in the Hierarchy pane) will open a preview window in the scene, so that you can see what your camera sees. At the moment our project doesn’t have anything for our camera to see (the light source is invisible), which makes for a rather bleak preview. By the end of this tutorial, we will have a neat game based on rolling a ball around a play area and collecting things. Follow the six-step guide over the page to set up the aforementi­oned ball, area and things.

Coding in the Unity editor

Well that was easy, but as you can probably imagine there’s going to have to be some code in order to breathe life into our newly created objects. Unity supports two languages directly: C# and UnityScrip­t (a modified form of JavaScript). Historical­ly, the Python-like Boo language was also available, but support for that was dropped last year. Unless you have a strong preference for JavaScript, most guides recommend using C#, as we shall do in this tutorial. It’s good to get into the habit of organising your project, so we’ll start by making a folder for our scripts. Right-click on the Assets folder in the Project panel and select Create > Folder and call it scripts. Our first task is to connect keyboard input with moving the

ball. To this end, open the scripts folder and right-click in the assets tab. Select Create > C# Script and rename it PlayerCont­roller.cs. We’re going to capitalise on Unity’s physics capabiliti­es here, so that key presses will add forces to our ball, rather than moving it directly, which will make for a much more realistic simulation. First, we need to bestow upon our ball some physical properties. Select the sphere – either from the Scene View or in the Heirarchy tab – then click on Add Component in the Inspector tab and select Physics > Rigid Body. We need to connect script and sphere, so with the sphere still selected drag the script from the Assets view into the Inspector. Double-clicking this script will open it in MonoDevelo­p, which may or may not be your preferred code editor, but it does integrate nicely with Unity so we’ll stick with it. Rather than an empty script, Unity will start you off with a template for your PlayerCont­roller object. This includes the functions Start() and Update() which are run when the object is initialise­d and once per frame respective­ly. We won’t use the Update() function, so you can delete that part and add in the required extra lines until it looks like this.

We’ve declared two variables at the start of the class, speed and rb . The public keyword means that the speed variable is accessible (and editable) from inside the Unity editor. You should be able to see it in the sphere’s Inspector tab, set it to 5 and adjust it to your preference later. Our rb variable stores a reference to the sphere’s Rigidbody component. Looking up these things is expensive so it makes sense to do it once at the beginning and re-use the reference as required. The FixedUpdat­e() function is more suited to adding forces than the standard Update() function, which is affected by framerate – it is called once per frame.

FixedUpdat­e() by comparison is called with a consistent interval, making it more suitable for physics updates (see http://bit.ly/UpdateandF­ixedUpdate). Here we check for keyboard input, using Input.GetAxis and use this to form a three dimensiona­l vector. Our ball isn’t going to move along the y axis (ie it remains on the plane), so our middle component here is 0.0f , which is how we express zero as a floating point number in C#. If you’ve ever dabbled with our Python Minecraft tutorials, then you’ll appreciate that Vector3 datatype is pretty similar to Minecraft’s Vec3 .

Adding a camera script

Our game is now sufficient­ly well-developed as to be tested now, which you can do using the ‘Play’ button in the topcentre. Roll the ball around (using the WASD keys) until you realise there’s more work to be done and then push the ‘Play’ button again to return to the editor.

It would be nice for the camera to follow the player around, so let’s make a script to do just that. First though, for the sake of good cinematogr­aphy, set the Main Camera’s position to 0, 5, -12 and set the x rotation to 12 degrees. Now select the Main Camera and then in the Inspector Tab use the ‘Add

Component’ button to create a new C# script, which we’ll call CameraCont­roller. Edit the script so that it reads:

Again, we’ve rebuffed the standard Update() function, this time in favour of LateUpdate(), which is called after the usual frame updates, and might otherwise cause camera oddities or slowdowns. All our camera controller does is maintain a constant vector between the camera and the player, almost as if it were carrying a selfie stick, only less awful. Before this code will work though, we need to set the Player object in the Camera Controller script. You’ll find this at the bottom of the Inspector tab.

We need to add some more pickups, which we’ll place freehand. Click on the word ‘Local’ in the top bar to switch to Global mode and duplicate our pickup a further 11 times, arranging them in a circle around the origin by dragging them. Using Global mode means that they move relative to the game’s axes rather then their own, which you will recall we rotated previously. Thus we can easily move our pickups around on the floor, rather than through it. Don’t worry if you don’t get a perfect circle here. Check out the box to animate these and make them seem more attractive (in the sense that if you were a sphere you’d want to pick them up).

Attach a new script to the pickup prefab and call it Rotator. The following line inside the Update() function is all that’s required to set our pickups spinning on all their axes:

transform.Rotate (new Vector3 (15,30,45) * Time. deltaTime);

Collision detection

We want to be able to pick up our pick ups, so we need to detect the collisions. Add the following code inside the PlayerCont­roller class, right before the final closing brace:

This will deactivate (disappear) any object that our sphere collides with, so long as it has a tag called Pick Up set. Let’s set for all our pickups in one fell swoop by using our prefab cube. Select it from the Assets tab and choose ‘Add Tag’ from the Tag drop-down in the Inspector tab. Use the plus (‘+’) sign to add a new tag called Pick Up (exactly as in the code snippet, above). We also need to set the Is Trigger property in our prefab’s Box Collider component, so that they are aware of each other. Now select one of the pickups and note that it (and all its brethren) have inherited this tag and trigger status. If you use the ‘Play’ button now you should find that our sphere no longer collides with the pickups, but that instead they disappear.

All our game is missing is a scoring system, and there’s just about enough space left to describe how to do that. First, we need to add a new variable count to our

PlayerCont­roller script. Declare it, and another variable countText that we’ll use in a moment, by adding the following lines below the speed and rb declaratio­ns: public Text countText; private int count; We’ll also need to initialise it, so set it to zero in the

Start() function:

count = 0;

And finally we need to increment it every time we pick up a penguin, er… pickup. This just requires this line right after we de-activate our pickups in the OnTriggerE­nter() function, inside the if clause: count = count + 1;

In order to display our score, we need to add a new text element to our game. From the Hierarchy tab, select Create > UI > Text. This will add a new Canvas object with the required child Text element. Select this element and click on the Anchor preset in the Rect Transform. While holding Alt and Shift choose the top-left option, to anchor our score text here. Now we need to hook this into our code, so once again edit the PlayerCont­roller script. First, we need to add the user interface namespace, so add this line below the first line

using UnityEngin­e; in the PlayerCont­roller script: Using UnityEngin­e.UI;

In the Start() function, below where we initialise­d our

count variable, add:

countText.text = “Count: " + count.ToString ();

All that’s required to finish this off is to attach the Text object to the PlayerCont­roller script, which is just a matter of selecting the Sphere in the Hierarchy, finding Player Controller (script) in the Inspector, and associatin­g our Text element with the public quantity Count Text.

Now you can build the project from the File menu and share it with your friends. We’ve seen how tremendous­ly powerful Unity is and we’re sure you lovely readers can have a lot of fun exercising your creative potential.

 ??  ?? Flippfly’s RaceTheSun is one of the many Unity-powered indie game successes, and it runs great on Linux.
Flippfly’s RaceTheSun is one of the many Unity-powered indie game successes, and it runs great on Linux.
 ??  ?? The release notes state, with the kind of understate­ment we Brits love, “Idle CPU usage is higher than it ought to be”. Running Unity on a laptop will be noisy.
The release notes state, with the kind of understate­ment we Brits love, “Idle CPU usage is higher than it ought to be”. Running Unity on a laptop will be noisy.
 ??  ??
 ??  ??
 ??  ?? Spend some time getting used to the perspectiv­e widget and working in three dimensions, placing the pickups is much easier from a top-down perspectiv­e.
Spend some time getting used to the perspectiv­e widget and working in three dimensions, placing the pickups is much easier from a top-down perspectiv­e.
 ??  ??

Newspapers in English

Newspapers from Australia