限免费插件开发游戏 Make A 2D Game in Unity3D Using Only Free Tools Part 1

来源:互联网 发布:淘宝店铺资金保护中 编辑:程序博客网 时间:2024/05/22 01:27

http://www.rocket5studios.com/tutorials/make-a-2d-game-in-unity3d-using-only-free-tools-part-1/


Make A 2D Game in Unity3D Using Only Free Tools Part 1


Posted on September 19th, by Tim Miller in iDevBlogADay, Tutorials, Unity3D. 31 comments

Make A 2D Game in Unity3D Using Only Free ToolsIn this iDevBlogADay post, I’m going to kick off a new tutorial series that’s aimed at making a 2D sprite-based game in Unity3D using only freely available tools, scripts and plugins. This isn’t the first 2D in Unity3D tutorial series I’ve done here – I previously did a 5 part series that used Sprite Manager 2 for the sprite display and animation duties. This time around, I want to show you how to make a game basically for free and I’m going to up the ante in this new series by adding in some other great plugins like iTween and A* Pathfinding.

Over the course of this series, we’re going to recreate one of my all time favorite C64 games: Lode Runner! I always wanted remake Lode Runner for my own amusement but also as a way to try out some things I haven’t figured out how to do yet – like creating an AI that can follow the player on ladders.

In this first installment, I’m going to introduce you to the tools we’ll be using and show you how to set them up in Unity. In the next part, we’ll dive in and start making the game. While we’ll be using the free versions of these tools, most of them also have paid options which unlock additional features.

Tools:

  • Unity3D: You probably already know that Unity3D is great tool for making 3D games, but it’s also pretty great at making 2D games with the addition of a few scripts and plugins. We’re going to be using the free version of Unity which will allow you to publish games to web as well as PC and Mac standalone but you can easily make the game work on iPhone or Android with a paid upgrade to those versions.
  • Orthello 2D Framework: There are several different sprite plugins available for Unity, the most popular being Sprite Manager 2 which I have used extensively and wrote about in my earlier 2D game tutorial series. I recently found myself looking for an alternative to SM2 and while doing research, @jeedee mentioned that he was quite satisfied with Orthello so I thought I’d try it out. In some ways it’s not as easy to use as some of the other plugins out there – you have to make your own sprite atlases for example – but for a free plugin it offers a ton of great features and will work perfectly for our 2D project.
  • iTween: iTween is my go-to animation system for every one of my projects here at Rocket 5. It’s ideal for animating everything from enemies to UI and it’s usually the first script I install when starting a new project.
  • A* Pathfinding Project: A* Pathfinding is probably the most widely used pathfinding system available for Unity. It’s fast, powerful, easy to use and since there’s a free version it’s perfect for our project.
  • TexturePacker: TexturePacker is a standalone app that makes it easy to create sprite sheets from your textures. You could use an image editing app like PhotoShop, Acorn or Gimp to make your atlases, but Orthello 2D recently added direct support for atlases generated by TexturePacker which should make things easier for us later on.

Starting A New Project:

  1. Install the latest version of Unity and then create a new project by going to File -> New Project, click theSet… button and browse to a location on your drive where you want to save your Unity projects, enter a name for the project and then click Save. Optionally you can select any packages that you want to import into the new project, I didn’t import any packages into my new project. Finally click the Create Projectbutton.
  2. Create a new folder in your Project view and name it “Scenes” and then save the current scene by going to File -> Save Scene As, open the Scenes folder you created in the previous step, name it “level1” and then click Save.

Installing Orthello 2D:

  1. Open the Asset Store by going to Window -> Asset Store, search for “orthello2d“. The page for the plugin should display, click the Download button. Or download the latest version from the website, unzip the archive and double click on orthello.unitypackage.
  2. When the Import Package window appears, make sure that all the checkboxes are checked and then click Import. After a few seconds you should see an “Orthello” folder in your Project view.

Orthello 2D Initial Setup:

The Orthello website has tons of detailed information on setting up and working with the plugin so be sure to take a look. Following are my simplified steps to get you started.

In order for Orthello to work in the scene, you’ll need to setup a few things first. Note that you will need to repeat these steps in every new scene you create.

  1. In the Unity Project view, go to Orthello -> Objects and then drag the OT prefab into either the Sceneview or the Hierarchy.

The OT prefab acts as a parent for Animations and Sprite Containers that we will be adding to the scene later on. Adding the OT object to your scene will also automatically make some changes to the Main Camara so that it will work properly for a 2D game – the main things are it changes the Projection to Orthographic and sets the Size to 332 (332 is kind of a weird size, but that’s the size that Orthello likes).

Installing iTween:

  1. Open the Asset Store again by going to Window -> Asset Store, search for “itween“. The page for the plugin should display, click the Download button.
  2. When the Import Package window appears, make sure that all the checkboxes are checked and then click Import. After a few seconds you should see an “iTween” folder in your Project view. If you want you can delete the “ReadMe!” and “Sample” folders if you want but they won’t hurt anything and it’s a good idea to look at the sample scene if you’ve never used iTween before.

Installing A* Pathfinding:

As I write this, the free version of A* Pathfinding is not available for download from the Unity Asset Store (the paid version is though).

  1. Go to the website, click on Download Latest Version and then click on A* Pathfinding Project in the Download area which should download a file named PathfindingProject_Free.unitypackage onto your computer.
  2. Double click on PathfindingProject_Free.unitypackage which will open the Importing Packagewindow in Unity. Make sure all of the checkboxes are checked and then click Import. You should now see a folder named “AstarPathfindingProject” in your Project view.

A* Pathfinding Initial Setup:

Be sure to read the “getting started” page in the A* Pathfinding Documentation for a full explanation of how to setup A*. Here are my simplified steps to get you going.

  1. Create a new empty game object by going to GameObject -> Create Empty.
  2. Make sure that the x,y,z position of the game object is at zero and then rename the object to “A*“.
  3. Add the Astar Path script to the game object by going to Component -> Pathfinding and then click onPathfinder.
  4. With the A* object selected in the Hierarchy, you should see Astar Path script’s options in the Inspector. At the top of the script you should see a message that says “Do you want to enable Javascript support?”. Since all of the scripts used in this tutorial are going to be written in C#, you can go ahead and click “No” (you can change this later in the settings if you want).

Conclusion:

If you followed all of the steps above, then your project should look something like this (click to see larger image).

The cool thing about the project is that you can use this as a starting point for creating all kinds of 2D games so keep this around as a base for starting new 2D projects (although be sure to check for the latest versions of the scripts).

Make A 2D Game with Unity3D Using Only Free Tools Part 2


Posted on October 4th, by Tim Miller in iDevBlogADay, Tutorials, Unity3D. 62 comments

Welcome to part 2 of this tutorial series on making a Lode Runner-style 2D game with Unity 3D. In part 1, I introduced you to a bunch of free tools and scripts that we’ll be using and showed you how to setup your project. In this post, I go over how to create the level sprites and build your first level.

Of all the Unity plugins we covered in part 1, the main plugin we’ll be focusing on in this installment of the series is Orthello 2D. Orthello was recently updated with a lot of cool new features (as I write this, 1.6a is the latest version) so make sure you’re using version 1.6a or newer.

Initial Project Setup

We need to make a few changes to the project settings before we start making the sprites.

Build Settings:

  • File –> Build Settings…
  • Click on Web Player and then click Switch Platform. (You could leave this set to PC and Mac Standalone if you prefer.)
  • Close the Build Settings window.

Player Settings:

  • Edit –> Project Settings –> Player
  • Under Per-Platform Settings click on the little world icon (assuming you set your platform to Web Player in the previous step).
  • Click on Resolution and Presentation and change the Screen Width to 800 and the Screen Height to600.

Render Settings:

Since you’re typically not going to use Unity’s lighting system in a 2D sprite-based game, we want to brighten things up in here by adjusting Unity’s default ambient light. This step is optional.

  • Edit –> Render Settings…
  • Click on Ambient Light and change the color to white (255, 255, 255, 255).

Initial Orthello 2D Setup

  • In the Unity Project tab, go to Orthello –> Objects and then drag the OT object into either the Scene or the Hierrachy tab.
  • In the Hierarchy tab, drop down the little arrow next to the OT object and then click on View.
  • Change the Pixel Perfect Resolution to 800 x 600 (same as we set for the Player Settings)
  • Change the Custom Size to 10

Now if you select the Main Camera in the Hierarchy, you’ll see that Projection is set to Orthographic and Size is set to 10. Orthello automatically changed the Projection from Perspective (Unity’s default setting) to Orthographic when you added the OT object into the scene. And When we changed the Custom Size on the Orthello View object to 10, it set the Main Camera’s Size to 10.

With a bit of experimenting, I found that with a screen resolution of 800×600 and an Orthographic Size of 10, a Cube at scale 1x1x1 will be exactly 30 pixels on screen which happens to be the exact size of the sprites we’re going to use to build the levels which should make it easy for us to stick to a grid when building levels.

At this point, your project should look something like the following image (click to see a larger image). Note that I also added a Cube to the scene for scale comparison.

Download the project up to this point.

Making The Level Sprite Atlas

Ok now that all that initial setup stuff is out of the way, it’s time to dig in and have some fun. The levels in Lode Runner were built using just a few simple tiles: Brick (digable), Concrete (un-digable), Ladder and Rope.

  • Download the source sprite .png’s and unzip the file somewhere on your hard drive.
  • Launch TexturePacker and then drag & drop all of the .png files from the sprites/level folder into the Sprites panel.
  • Then select all of the .png files in the sprites/shoot folder and drag those into the Sprites panel too.

Texture Settings / Layout:

  • Set Algorithm to Basic
  • Uncheck Trim
  • Uncheck Enable Auto Alias.

Texture Settings / Output:

  • Leave the Data format set to cocos2d.
  • Under Data File, click the little “…” button and browse the location in your project’s Asset folder where you want to store your sprites (I put mine in Assets/SpriteAtlases), name the file “level” and then click Save.
  • TexturePacker automatically adds the .plist extension to the Data File, but Unity wants the file to be .xml. So in the text field, replace .plist with .xml.
  • The Texture File path should already be set to the same location as the .xml file except that it will have a .png extension so there’s nothing to do there.

If you followed the steps above, then your settings in TexturePacker should look like this (click the image to see a larger version):

Now if you click the Publish icon in TexturePacker and then switch back to Unity, you should see aSpriteAtlases folder in the Project tab with the sprite atlas and a sprite data files inside.

We need to make a couple of changes to the sprite atlas in Unity so that it looks correct.

  • Select the level.png file in the Project tab. In the Inspector change the Filter Mode to Point.
  • Click the Override for Web box, set the Format to Truecolor and then click Apply.

Making The Level Sprites

Now it’s time to dig into Orthello and turn the atlas into sprites.

The Sprite Container:

  • In the Unity Project tab, expand the Orthello folders: Orthello –> Objects –> Sprites –> SpriteAtlas and then drag the SpriteAtlas-Cocos2D object into the Hierarchy.
  • In the Hierarchy tab, expand the newly created OT object and then the Containers object and you will see your new container with a name something like “Container (id=-6840)“. This is the Container that will hold all of our level sprites from the atlas we made so you can rename the Container to something obvious like “level“.
  • Drag the level.png from the Project, SpriteAtlases folder and drop it on the “OTSprite Atlas Cocos 2D” scripts Texture slot.
  • Drag the level.xml from the Project, SpriteAtlases folder and drop it on to the Atlas Data File slot. Now if you drop down the little Atlas Data arrow, you should see that it’s populated with all the sprite atlas data that TexturePacker generated for us.

Making An Animated Brick Tile:

The brick needs to have some animations on it that will play when it’s destroyed and when it regenerates so we need to make an Animation.

  • Drag an Animation object from Orthello –> Objects –> Sprites into the Hierarchy. This will add a new object under OT –> Animations named something like “Animation (id=-4320)“. Rename this object to “level anims“.
  • With the new OTAnimation still selected, adjust the settings to match those in the following image.
  • Under Framesets, set the Size to 3
  • To populate the Container field, drag & drop the “level” object from OT –> Containers on to the Container field.

  • Next find the AnimatingSprite object in Orthello –> Objects –> Sprites and drag it into the Hierarchy, this will make a new object in the scene with a name like “Animating Sprite (id=-23050)“. Rename this object “brick“.
  • With the new brick object still selected in the Hierarchy, drag the “level anims” object on to the Animationslot. The Sprite Container slot should automatically fill with a reference to the “level” container object, if it doesn’t you can drag & drop that onto the slot.

Now you should see a brick sprite in your scene and if you press Play in Unity, the sprite will animate through all of the frames in the animation. We don’t want the animation to play on start so uncheck the Play On Startcheckbox.

Note: if you don’t see the brick in the Game view, make sure that the brick’s Scale is set to 1, 1, 1 (sometimes when creating a new Orthello object, the X and Y scale are set to a very small number).

Adding Collision To The Brick:

We’re going to need some collision on the brick later on so that the player knows when he/she’s standing on the ground.

  • With the brick object still selected in the Hierarchy, check the Collidable checkbox. This will automatically add a Box Collider and Rigidbody component to the sprite.
  • We also need to Tag the object with a specific tag and add it to a Layer. Go to Edit –> Project Settings –> Tags to open the Tag Manager.
  • Under Tags at the very top, drop down the little arrow and then type “Ground” (without the quotes) into theElement0 field and press enter. We’re going to need a few more tags later on so while we’re here, add another tag called “Ladder” and “Rope“.
  • We need some Layers too so under User Layer 8, type Ground and under User Layer 9 type Ladder.
  • Click on the brick object in Hierarchy and the drop down the Tag list in the Inspector and select Ground. Then click on the Layer drop down and select Ground from that list.

Turn It Into A Prefab:

Later on in the tutorial series we’re going to be adding some stuff to the brick object and making some changes so it’s a good idea to turn the object into a Prefab so that if you build a level with the brick and then and then want to make changes to it later, the changes will be applied all the prefab brick objects in your level. Making a prefab is super easy and will save you a ton of time later on.

  • Create a new folder in your Project and name it “Prefabs“.
  • Drag the brick object from the Hierarchy and drop it into the Prefabs folder in the Project tab.

Making The Static Level Sprites

Next we need to make the concrete, ladder and rope tiles. We’re going to use the same Container for these that we made before but instead of displaying them with an AnimatedSprite, we’re going to use the Sprite object.

Concrete Tile:

  • If your brick object is still sitting in the center of the Scene, move it to the side so it’s out of the way.
  • Drag & drop the Sprite object from Orthello –> Objects –> Sprites into the Hierarchy or Scene which will create a new object named something like “Sprite (id=-3700)“. Rename that object to “concrete“.
  • Drag the level object that we created earlier from OT –> Containers and drop it on to the Sprite Containerslot in the Inspector.
  • Your sprite will appear but it looks like the brick sprite that we made before, that’s because the brick is the first texture on the Sprite Atlases index. Click and hold your mouse over the word “Frame Index” in the inspector (with the concrete object selected) and then drag the mouse to the right to scroll through the textures on the sprite atlas. The concrete texture is at index 14 so set it to that. The sprite should now look like a solid brick.
  • Check the Collidable checkbox to add collision to the object.
  • Drop down the Tag list in the Inspector and select Ground. Then click on the Layer drop down and selectGround from that list.
  • Drag the concrete object from the Hierarchy into the Prefabs folder in the Project tab to create prefab from the object.

Ladder and Rope Tiles:

The Ladder and Rope tiles follow most of the same steps as the Concrete tile.

  • Move concrete tile out of the way if it’s still sitting in the center or the Scene view.
  • Drag & drop a Sprite object from Orthello –> Objects –> Sprites into the Hierarchy or Scene and rename the object to “ladder“.
  • Drag the level object that we created earlier from OT –> Containers and drop it on to the Sprite Containerslot in the Inspector.
  • Change the Frame Index to 15, the sprite in the Scene view should now look like a ladder segment. That’s all we need to do on the ladder tile for now.
  • To make the Rope tile, duplicate the ladder sprite in the Hierarchy and then rename it “rope“.
  • Change the Frame Index to 17 so that it looks like a black cube with a white line across the top (that’s our rope tile!).
  • Now make prefabs from the ladder and rope by dragging each of the objects from the Hierarchy into the Prefabs folder in the Project tab.

Making The Bottom Border:

Now we have all the sprites necessary for making levels, but before we start we need to make a border object that will sit at the bottom of the screen. The border will give the player and enemies something to stand on if there are missing bricks along the bottom row and it will also give us something to snap to so that the levels will adhere to a nice grid.

  • Go to Game Object –> Create Other –> Cube and rename it to “border bottom
  • Change the Transform Position to X: 0, Y: -10.3, Z: 0
  • Change the Transform Scale to X: 26, Y: 1, Z: 1
  • Drag and drop the border bottom object from the Hierarchy into the Prefabs folder in the Project tab to turn it into a prefab.

A small amount of the cube should be visible above the bottom of the Game view and it shouldn’t quite be all the way to each edge. The cube is pretty ugly with the default white material, so let’s make a material that matches the color of the bricks.

  • Create a new folder in the Project tab and name it Materials.
  • Right click on the Materials folder and go to Create –> Material and then rename the new material “border
  • Select the border material and then in the Inspector click on the white area beside the little eye dropper icon, this will open up the color picker.
  • Change the RGBA settings to R: 159, G: 2, B: 0, A: 255 and then close the color picker.
  • Drag the border material and drop it on to the border bottom object in the Hierarchy to apply the material. The border should now be the same color as the bricks.
  • With the “border bottom” object still selected, click on Apply next to Prefab in the Inspector, this will update the prefab with the new changes.

Change The Background Color

We’re almost ready to make a level, but first lets change the background color to black.

  • Select the Main Camera and then click on the color swatch next to Background.
  • Change the RGBA settings to 0,0,0,255. The background in the Game window should now be black.

Making A Level:

Whew! It took a few steps, but now you have everything you need to build a bunch of levels. Well almost everything – you still need a player, enemies, a pickup and a few other things which we’re going to cover later on in the series.

At this point you can just start duplicating the brick, concrete, ladder and rope tiles around the scene to make a level. BUT before you do, here are a few tips:

  • In the Scene view, click on the drop down list directly under the Scene tab – it might say something like “Textured” and change the option to Tex-Wire.
  • You can use Vertex Snap to easily align objects – in the Scene view hold down the V key and hover the mouse over any of the 4 corners on one of your tiles and you’ll see that the manipulator will snap to the closest corner. Click the left mouse button when the handle is over a corner of the sprite that you want to snap from and then drag the object to another sprite corner to align it tightly with that tile.
  • Remember that bottom border cube we made before, well you can use that as a base line for snapping your cubes so that you can build the entire level on a grid. Grab one of your tiles and snap the lower left corner to the upper corner of the bottom border object. Note that you don’t have to worry about snapping on the Z axis since Orthello doesn’t allow you to move objects along the Z axis.
  • You can also select several tiles at the same time either with shift+left click or by dragging an area around a bunch of tiles. Duplicate those tiles and then use Vertex Snap to snap them to other tiles in the scene.

Here’s what my initial scene looks like as I start by building the level from the bottom border object (click to see a larger version):

And here’s what a finished level looks like (click to see a larger version):

Conclusion:

I hope you enjoyed this post and learned a little more about how to make 2D games with Unity. In the next post we’re going to be adding a playable character so you can actually run around in the levels.

If you like this post, please be sure to say hi in the comments and follow me on Twitter and Facebook. Your support helps to keep these tutorial coming. This blog post is part of iDevBlogADay, a collection of indie developers writing about their development experiences.

Download the project up to this point.

Make A 2D Game With Unity3D Using Only Free Tools Part 3


Posted on October 17th, by Tim Miller in iDevBlogADay, Tutorials, Unity3D. 65 comments

Welcome to Part 3 in this series on making a 2D sprite-based game with Unity 3D. In Part 1 I introduced you to the tools we’ll be using to make a Lode Runner style action game and in Part 2 we created the level sprites and built our first level. In this tutorial we’re going to be adding in the player, hooking up the scripts and adding collision to the ladders and ropes so that you’ll finally be able to run the character around in your levels.

This tutorial assumes that you have already followed along with Part 2 of this series so your project should be ready to continue on with the steps below. If you haven’t already done Part 2, you should go back and do that first so you can get a full understanding of how everything fits together. If you’d rather skip ahead, you can download the project up to this point. You can also click here to see how the game will look at the end of Part 3.

Making the Player Sprite Atlas

If you’ve been following the series, I know you’re excited to get the player character running around in the game, so the first thing we need to do is create a sprite atlas in TexturePacker.

  • Download the source sprite .png’s and unzip the file somewhere on your hard drive. If you already downloaded the sprites and added them to your project in Part 2, then you can skip this step.
  • Launch TexturePacker and then drag & drop all of the .png files from the sprites/player folder into theSprites panel.

Texture Settings / Layout:

  • Set Algorithm to Basic
  • Set Border Padding to 1
  • Set Shape Padding to 1
  • Uncheck Trim

Texture Settings / Output:

  • Leave the Data format set to cocos2d.
  • Under Data File, click the little “…” button and browse to the location in your project’s Asset folder where you want to store your sprites (I put mine in Assets/SpriteAtlases), name the file “player” and then clickSave.
  • TexturePacker automatically adds the .plist extension to the Data File, but Unity wants the file to be .xml. So in the text field, replace .plist with .xml.
  • The Texture File path should already be set to the same location as the .xml file except that it will have a.png extension so there’s nothing to do there.

If you followed the steps above, then your settings in TexturePacker should look like this (click the image to see a larger version):

Now if you click the Publish icon in TexturePacker and then switch back to Unity, you should see aplayer.png file and a player.xml file in the SpriteAtlases folder in the Project view.

If you don’t already have the project open in Unity, open it now and then load the scene that you created in Part 2 (eg. level1.scene).

We need to make a couple of changes to the sprite atlas in Unity so that it looks correct.

  • Select the player.png file in the Project tab. In the Inspector change the Filter Mode to Point.
  • Click the Override for Web box, set the Format to Truecolor and then click Apply.

Making the Player Sprite

Now we’re ready to turn the player’s sprite atlas into animated sprites using the Orthello 2D plugin.

The Sprite Container:

  • In the Unity Project tab, expand the Orthello folders: Orthello –> Objects –> Sprites –> SpriteAtlas and then drag the SpriteAtlas-Cocos2D object into the Hierarchy.
  • In the Hierarchy tab, expand the OT object and then the Containers object and you will see your new container with a name something like “Container (id=-6840)“. This is the Container that will hold all of ourplayer sprites from the atlas we made so you can rename the Container to something obvious like “player“.
  • Drag the player.png from the SpriteAtlases folder and drop it on the “OTSprite Atlas Cocos 2D” script’sTexture slot.
  • Drag the player.xml from the Project, SpriteAtlases folder and drop it on to the Atlas Data File slot. Now if you drop down the little Atlas Data arrow, you should see that it’s populated with all the sprite atlas data that TexturePacker generated for us.

Setting Up The Player Animations:

Now we need to assign all of the frames from the sprite atlas to individual animations.

  • Drag an Animation object from Orthello –> Objects –> Sprites into the Hierarchy. This will add a new object under OT –> Animations named something like “Animation (id=-4320)“. Rename this object to “player anims“.
  • With the new “player anims” OTAnimation still selected, adjust the settings to match those in the following image. To populate the Container field, drag & drop the “player” object from OT –> Containers on to theContainer field.

Click the image to see all of the animation settings:

Making The Player Sprite

  • Next find the AnimatingSprite object in Orthello –> Objects –> Sprites object in the Project tab and drag it into the Hierarchy, this will make a new object in the scene with a name like “Animating Sprite (id=-23050)“. Rename this object “player“.
  • With the new player object still selected in the Hierarchy, drag the “player anims” object on to theAnimation slot. The Sprite Container slot should automatically fill with a reference to the “player” container object, if it doesn’t you can drag & drop that onto the slot.
  • Now you should see the player sprite in your scene and if you press Play in Unity, the sprite will animate through all of the frames in all of the animations. We don’t want the animation to play on start so uncheck the Play On Start checkbox.

Adding Collision To The Player

In order for the player to collide correctly with the ladder and rope colliders we’ll be creating later, we need to set the following.

  • With the the player “OTAnimating Sprite” still selected in the Hierarchy, check the check box next toCollidable. This will automatically add a Rigidbody component to the object.
  • Click the dropdown list next to Physics and select Custom from the list.
  • Under Transform, set the Scale Z to 1.
  • Change the Depth to -1.
  • Under Box Collider, set Center Y to -0.1 and Z to 1. Change Size X to 0.45Y to 0.6 and Z to 0.4.

If you followed the steps above, the settings on the player sprite should look like the following image.

Click on the image to see all of the settings:

Changing the Depth to -1 and the Center Z to 1 on the Box Collider will position the Collision at 0 on the Z axis while moving the player sprite 1 unit towards the camera. This has 2 effects: it makes sure that the player will always be visible in front of the level sprites while keeping the collision at 0 on the Z so that it will collide with the ladder and rope triggers. It sounds kinda strange, but you can see how it should look in this screen shot:

2dGamePt3 Player Collision

Setting Up The Shooting Animation

We need to add another animating sprite so that when you press the fire button, you’ll see a bullet blob animate from the player and hit the ground.

The Shoot Animation:

  • Drag an Animation object from Orthello –> Objects –> Sprites into the Hierarchy. This will add a new object under OT –> Animations named something like “Animation (id=-4320)“. Rename this object to “shoot anim“.
  • With the new “shoot anim” OTAnimation still selected, adjust the settings to match those in the following image. To populate the Container field, drag & drop the “level” object from OT –> Containers on to theContainer field. Remember that we already added the shoot sprite animation to the level sprite atlas in Part 2 of the series.

2dGamePt3 Shoot Sprite Animations

The Shoot Sprite

  • Next find the AnimatingSprite object in Orthello –> Objects –> Sprites in the Project tab and drag it into the Hierarchy, this will make a new object in the scene with a name like “Animating Sprite (id=-23050)“. Rename this object “shoot“.
  • With the new shoot object still selected in the Hierarchy, drag the “shoot anim” object on to the Animationslot. The Sprite Container slot should automatically fill with a reference to the “level” container object, if it doesn’t you can drag & drop that onto the slot.
  • Set the Transform Position X to -1 so that the sprite is position to the left of the player’s sprite.
  • Set the Depth to -1 so that the sprites will appear in front of the level sprites.
  • Set the Frame Index to 18.

Now you should see the shoot sprite in your scene and if you press Play in Unity, the sprite will animate through all of the frames in all of the animations. We don’t want the animation to play on start so uncheck thePlay On Start checkbox.

We only want to see the shoot sprite when the player is actually shooting so uncheck the checkbox next toMesh Render on the shoot sprite. This will hide the sprite in the scene until we show it again later with a script.

Parenting The Shoot Sprite

We want the sprite to move with the player and we also need to flip the sprite so that it’s either on the player’s left or right side depending on which way the character is facing.

  • Go to Game Object –> Create Empty
  • Rename this object to “shoot parent” and make sure the X, Y, Z Position on the object is set to zero.
  • In the Hierarchy, drag and top the shoot sprite on to the shoot parent so that the shoot sprite becomes a child of the shoot parent object.
  • Drag and drop the shoot parent object on to the player sprite so that it’s a child of the player.

If you followed all the steps so far, your Hierarchy should look something like the following image. Note that I put all of my level tiles under an empty game object named LEVEL to keep things organized.

2dGamePt3 Player Parenting

Note that in order for the scripts to work, the child objects under the player must be named exactly as shown in the above image.

Hooking Up The Scripts

We’re finally ready to add the scripts so that the player can move!

  • Download the player scripts and unzip the file somewhere on your hard drive.
  • Drag the Scripts folder from the .zip into your project’s Asset folder.
  • Create an empty game object by going to Game Object –> Create Empty
  • Rename the new object to something like “Scripts“.
  • Drag and drop the xa.cs file from the Project tab onto the Scripts object in the Hierarchy.
  • Drag and drop the player.cs and the playerAnims.cs files from the Project tab on to the player object in the Hierarchy.
  • Make sure that the player is positioned above a brick tile so that she has something to stand on. Remember that it’s the player’s Box Collider that actually collides with objects in the world and not the visible sprite object, so the box will be positioned at something like 0,0,-1 (X and Y can be anywhere in the level but Z should always be -1).

Now if everything is setup correctly, when you press Play in Unity the player should stand on a brick tile without falling through it. And if you press left and right on the keyboard the player should move and the run animations should play.

Describing how the scripts work is beyond the scope of this tutorial, but I did add comments to the scripts that should hopefully help you understand how everything is working. If you have questions about anything in the scripts, please feel free to ask in the comments below or email me directly.

Adding The Ladder Colliders

In order for the ladders to work, we need to add colliders to them.

Creating A Ladder:

  • Go to GameObject –> Create Other –> Cube
  • Rename the Cube to something like “Ladder“.
  • Open the Tag Manager by going to to Edit –> Project Settings –> Tags
  • Under Tags in the next available slot (probably Element 1) type “Ladder” and then in the next slot after that, type in “Rope” (without the quotes).
  • While we’re here, we need to add another layer. Under the next empty User Layer (probably User Layer 9), type “NoDraw” (without the quotes).
  • Now click on the Ladder cube you created before and change the Tag to “Ladder” and then change the Layer to “NoDraw“.

Hiding Objects In The Game View:

You’ve probably noticed that the Ladder collider is visible in the Game view but we don’t want to see these in the actual game. To hide them, we need to make a change to the camera.

  • Click on the Main Camera object in the Hierarchy.
  • Under Camera, drop down the list next to Culling Mask and click on “NoDraw” to deselect it. Now any object that is in the “NoDraw” layer will be hidden in the Game view.

Sizing And Positioning The Ladder:

Every ladder in the scene needs to have one of these Ladder colliders and we need to adjust the size of the Ladder colliders to match the height of each of the ladders in the level. The ladder collider needs to be 1 unit taller than the visible ladder – so if your ladder is 4 tiles (sprites) tall, then the collider needs to be 5 units tall.

  • Assuming your ladder is 4 sprites high: Select the Ladder collider and change the Scale Y to 5 (1 unit taller than the visible ladder).
  • Snap the Ladder collider to one of the lower corners of the bottom sprite using the Vertex Snap feature in Unity.
  • You can duplicate this object, resize the Y and snap it to all the other ladder sprites in your level.

Your ladder should look like this (click to see a larger version):
2dGamePt3 Ladder Trigger

Now if you press Play in Unity and then walk the player over to the ladder, she should be able to climb up and down the ladder, the player’s sprite should be playing the climb animation and you should be able to exit the ladder at the top and bottom levels and also fall off the ladder if you exit somewhere in the middle.

Adding the Rope Colliders

The rope colliders follow pretty much the same setup as the ladders.

Creating A Rope:

  • Go to GameObject –> Create Other –> Cube
  • Rename the Cube to something like “Rope“.
  • Change the Tag to “Rope” and then change the Layer to “NoDraw“.

Sizing And Positioning The Rope:

Like the Ladders, every rope in the scene needs to have one of these Rope colliders. But unlike the Ladders, the Rope colliders must be the same width as your rope sprites.

  • Assuming your rope is 4 sprites wide: Select the Rope collider and change the Scale X to 4 (Y and Z scale should be 1).
  • Snap the Rope collider to one of the lower corners of the bottom sprite using the Vertex Snap feature.
  • You can duplicate this object, resize the X and snap it to all the other rope sprites in your level.

Your rope should look like this (click to see a larger version):
2dGamePt3 Rope Trigger

Now if you press Play in Unity and then walk the player over to the rope, she should be able to climb left and right along the rope, you should see the rope hang animation playing and if you press the down arrow while hanging from the rope, she should let go of the rope and fall.

Conclusion

Now you have everything you need to make levels that support the player’s full suite of movements: running, ladder climbing and rope shimmy. In the next tutorial, we’re going to be adding the scoring system, breaking out brick tiles and picking up objects.

You can download the project up to this point and you can play the web version of the project here.

If you like this post, please be sure to say hi in the comments and follow me on Twitter and Facebook. Your support helps to keep these tutorial coming. This blog post is part of iDevBlogADay, a collection of indie developers writing about their development experiences.

Regarding The AI:

When I began this series, It was my intention to include enemies that could follow the player around the level using behaviors similar to the original Lode Runner game. However my time has become increasingly limited and my programming skills aren’t fully up to the task of recreating their AI so I might not be able to get AI into this the series.

If you are a programmer who would like to contribute an AI behavior solution to this tutorial series, please contact me.

Make A 2D Game With Unity3D Using Only Free Tools Part 4


Posted on November 14th, by Tim Miller in iDevBlogADay, Tutorials, Unity3D. 24 comments

Make A 2D Game In Unity3d Part 4This is part 4 of our tutorial series on making a 2D game in Unity3D with freely available tools and plugins. Part 1 introduced you to the tools we’re using, in Part 2we built our first level and in Part 3 we hooked up the control scripts and setup the ladders and ropes so that the player can navigate levels. In this article we’re going to create a pickup item, hook up the scoring system and add the interface text which reports score, lives and level.

Hopefully you already went through part 2 and part 3 of the series, if you haven’t already you might want to go back and do them now so everything in this part will make sense.

If you’d rather skip ahead, you can download the project up to this point. You can also click here to play the game as it will be at the end of Part 4.

Adding The Scoring and Pickup Scripts

The game is working great so far – the player can move, climb ladders and shimmy across ropes. Now we’re going to add a “gold chest” pickup item and an interface to track scoring, player lives and the current level.

  • Download scoring and pickup scripts and unzip the file somewhere on your hard drive.
  • Copy Scoring.cs and Pickup.cs from the extracted .zip file and paste them into your project’sAssets/Scripts folder.

Modifications To Existing Scripts:

You’re going to need to make a few changes to the scripts from part 3 so that these new scripts will work.

  • Open xa.cs script and then uncomment the first line in the Class:
?
1
publicstaticScoring sc;
  • In the Start function, uncomment this line:
?
1
sc = (Scoring)(this.gameObject.GetComponent("Scoring"));
  • Open Player.cs, find the OnTriggerEnter function (line 256) and then uncomment the following code block:
?
1
2
3
4
5
6
7
8
if(other.gameObject.CompareTag("Pickup"))
{
    if(other.GetComponent<Pickup>())
    {
        other.GetComponent<Pickup>().PickMeUp();
        xa.sc.Pickup();
    }
}

Making The Pickup Sprite

You might remember from part 2, that you already added the pickup.png to the level sprite atlas and then created a level container object that points to the sprite atlas so we don’t need to do any additional Container setup to create the pickup.

  • Drag & drop the Sprite object from Orthello –> Objects –> Sprites into the Hierarchy or Scene which will create a new object named something like “Sprite (id=-3700)“. Rename that object to “pickup“.
  • Drag the level object that we created in part 2 from OT –> Containers and drop it on to the Sprite Containerslot in the Inspector.

Your sprite will appear but it looks like the brick sprite that we made before, that’s because the brick is the first texture on the Sprite Atlases index.

  • Click and hold your mouse over the word “Frame Index” in the inspector (with the pickup object selected) and then drag the mouse to the right to scroll through the textures on the sprite atlas. The pickup texture is at index 16 so set it to that. The sprite should now look like a a white rectangle with a red box in the center and a black background.

Adjusting The Collision:

The sprite is a square, but we only want the object to be picked up only when the player touches the white part of the pickup.

  • Check the Collidable checkbox to add collision to the object.
  • Open up the drop down list next to Physics and then select Custom.
  • Under Box Collider, set the Center Y to -0.15Size X to 0.8 and Size Y to 0.5. Leave Size Z set to 0.4.

Setting The Tag:

We need to tag the pickup so that the player will trigger it when touched.

  • Create a new tag by going to Edit –> Project Settings –> Tags
  • Add a new Tag in the Tags list (probably in Element 3 if you’ve been following the series) named “Pickup” (without the quotes). It’s important that the name is correct since Player.cs looks for this exact name.
  • Select the pickup object in the Hierarchy, then click on the drop down list next to Tags at the top of the Inspector and then select Pickup.

Add The Script and Make It A Prefab

Now we just need to add the Pickup.cs script to the sprite so that it will get “picked up” when the player touches it and we also need to turn it into a prefab so that it’s easy to place in all your levels.

  • Drag the Pickup.cs script from the Project Scripts folder and drop it on to the pickup sprite in the Hierarchy.
  • Drag the pickup object from the Hierarchy into the Prefabs folder in the Project tab to create prefab from the object.

The pickup is designed so that you can snap the bottom edge (the black part) of the sprite to the top edge of a brick sprite the white part of the powerup will be the correct height from the top of the brick. Duplicate your new pickup prefab a few times and place it around you level.

If you followed all of the steps so far, your pickup should look like this:
2dGamePt4 pickup

Add The Interface Text

At this point if you place the pickup in your level so that the player can pick it up, the sprite will disappear correctly as if he picked it up, but you’ll get some errors in the console because the Scoring script isn’t in the scene yet and we don’t have any UI to report the score. So let’s fix that.

  • First add the Scoring.cs script to the scene: Drag Scoring.cs from your Project’s Scripts folder and drop it on to the Scripts object in the Hierarchy. If you select the Scripts object, you’ll see that the Scoring script has a bunch of slots for text objects that we need to add – but first we need to create the text objects.
  • Download the G7 Silkworm font and unzip the file somewhere on your computer. This font isn’t exactly the same as the one used in the original Lode Runner game, but it’s pretty close. If there’s another font you’d rather use, go for it. And if you find a font that’s closer to the Lode Runner font, please let me know in the comments.
  • Create a new folder in your Assets folder named Fonts, locate the silkworm.TTF font on your hard drive and then copy it into the Assets/Fonts folder.
  • In Unity, select the silkworm font in your Project’s Fonts folder and then in the Inspector set the Font Sizeto 26.

Adding The Score Text:

  • Drag the silkworm font from the Fonts folder in the Project panel and drop it into the Hierarchy. This will automatically create a new GUI Text object in the Hierarchy using the silkworm font.
  • Rename the object to “Score Label
  • In the Text field under GUIText in the Inspector, type “SCORE” in all caps without the quotes. The Silkworm font only has uppercase letters so don’t try to use lowercase letters.
  • When you add a font to the scene, the X and Y position are automatically set to X 0.5 and Y 0.5, but we’re going to set the position of our fonts using the Pixel Offset so reset the X and Y Position to 0.
  • Change Pixel Offset X to 16 and Pixel Offset Y to 592. This should position the SCORE text to the upper left hand corner of the Game view (note you won’t see the text in the Scene view so look at the Game view to help position the text).

We also want to keep the scene nicely organized and make it a little easier to hook up the interface objects to the Scoring script later on. You’re going to make the Score Label object a child of the Scripts object and then you’ll duplicate each of the other text objects from this one in order to save a few of the setup steps.

  • Select the Score Label object in the Hierarchy and then drag and drop it onto the Scripts object in the Hierarchy so that it becomes a child of the Scripts object.
  • Expand the little arrow next to the Scripts object, select Score Label object and then duplicate it.
  • Rename the new text object to “Score Value“.
  • Change the Text to 0000000 (7 zeroes).
  • Change the Pixel Offset X to 150 and leave the Y set to 592.

Adding The Lives Text:

  • Select either the Score Label or the Score Value text object and duplicate it.
  • Rename the new text object to “Lives Label
  • Change the Text to LIVES.
  • Change the Pixel Offset X to 348 and leave Y set to 592.
  • Duplicate Lives Label object and rename it to “Lives Value“.
  • Change the Text to 000 (3 zeroes).
  • Change the Pixel Offset X to 480 and leave Y set to 592.

Adding The Level Text:

  • Select one of the other text objects you already created and duplicate it.
  • Rename the new text object to “Level Label
  • Change the Text to LEVEL.
  • Change the Pixel Offset X to 576 and leave Y set to 592.
  • Duplicate Level Label and rename the new object to “Level Value
  • Change the Text to 000 (3 zeroes).
  • Change the Pixel Offset X to 710 and leave Y set to 592.

Hooking Up The Scripts:

Now we need to connect the interface text objects to the Scoring script.

  • Select the Scripts object in the Hierarchy. Under the Scoring script in the Inspector, you’ll see slots for each of the GUIText objects we just created.
  • Select each of the text objects from the Hierarchy and drag and drop them into the corresponding slot on the Scoring script. For example, drag Level Label and drop it on to the Level Label Text field.

Once all of the text objects are connected to the Scoring script, press Play in Unity. You should see the SCORE, LIVES and LEVEL text turn to a red color that matches the border color and the number of lives should change to 005 and the level number should change to 001.

Now if you run the character over a pickup object in the game, the Score should increase by 250.

Make The Top Border

To help keep the interface text separate from the gameplay area, we’re going to add a thin border just under the interface text.

  • Create a new cube by going to Game Object –> Create Other –> Cube
  • Rename the object to “border top“.
  • Set the Transform Position X to 0to 8.7 and Z to 1.
  • Set the Scale X to 26Y to 0.2 and Z to 1.
  • Find the border material in the Materials folder and then drag and drop it on to the border top object. We created the border material in a previous article.

If you followed all of the steps above, then your Hierarchy and Inspector (with the Scripts object selected) should look the following:

2dGamePt4 Scoring Text

Creating The GLOBAL Prefab

Next we want to do some things to keep the scene nicely organized and also to make it easy to add the key components to any new levels that you create. We’re going to create a GLOBAL prefab that contains the Main Camera, the Scripts (which includes the interface text objects) and the top and bottom borders.

  • Create an empty game object by boing to Object –> Create Empty, zero out the transforms so that it’s at 0,0,0 on the X,Y,Z and then rename the object to “GLOBAL“.
  • Select the Main Camera in the Hierarchy and then drag and drop it onto the GLOBAL object so that the Main Camera becomes a child of GLOBAL.
  • Select the Scripts object in the Hierarchy and drag and drop it onto the GLOBAL object.
  • Select the border bottom and border top objects (make sure they’re not already a child of some other game object first) and drag and drop them onto the GLOBAL object.

That’s everything we need for the GLOBAL object, so now let’s turn it into a prefab that can be easily added to other levels and updated later if we need to make changes.

    Select the GLOBAL object in the Hierarchy and then drag and drop it onto the Prefabs folder in the Project panel.

    Creating The Player Prefab

    In Part 3 of the series, I forgot to create a prefab from our player character, so let’s do that now if you haven’t already.

    • Select the player object in the Hierarchy and zero his Transform position X to 0, Y to 0 and leave the Z position set to -1. This step is optional, I just like to have my game objects centered when I initially create a prefab.

    If you’ve followed all of the steps so far, then your Project and scene Hierarchy should look like the following image:
    2dGamePt4 Global Prefab

    Conclusion

    We’re getting a lot closer to having a complete game. Over the course of the next few tutorials I hope to add enemy AI (still working on a good solution for them), breakable bricks, a front end interface, an exit ladder (for exiting levels), some kind of manager for keeping track of your current level and a few other things like a game over screen. Let me know in the comments if there are other things you’d like to see covered.

    If you followed all of the steps so far, then your game should look something like this image (click to see a larger version):

    2dGamePt4 Game Shot

    You can download the project up to this point and you can play the web version of the project here.

    If you like this post, please be sure to say hi in the comments and follow me on Twitter and Facebook. Your support helps to keep these tutorial coming. This blog post is part of iDevBlogADay, a collection of indie developers writing about their development experiences.



Make A 2D Game With Unity3D Using Only Free Tools: Beginning Enemy AI With A* Pathfinding


Posted on January 23rd, by Tim Miller in iDevBlogADay, Tutorials, Unity3D. 29 comments

Make a 2d game in unity3d part 5In This installment of our 2D tutorial series, we will be adding enemy AI to our Lode Runner clone using A* Pathfinding. This post has been guest written by Adrian Seeto of Fun Mob Games who was also kind enough to write the AI scripts that are a huge part of bringing the game to life.

Adding the enemy AI required changes to many of the scripts that we added in the previous tutorials. You can download the complete project here which has been rebuilt to support the new prefab system in Unity 3.5x. If you’re using an older version of Unity (pre 3.5), then you should download this version. You can also follow the steps below to update your existing project. I recommend following along with the tutorial as there’s tons of great information on implementing the AI with A*. You can also play the game as it will be at the end of this tutorial here.

Installing the A* Package

  1. Import the free version of Aron Granberg’s A* Pathfinding Project into Unity3d
  2. Create an empty GameObject and rename it A*. Make sure it’s positioned at 0,0,0
  3. Drag the /AstarPathfindingProject/Core/AstarPath.cs file onto the A* GameObject
  4. Click on the A* GameObject and disable the “Allow Javascript” option

Importing game C# scripts

Many of the scripts have been modified since Part 4 of this series, so you’ll need to update them. If you’ve made changes to your own scripts then you’ll need to merge your changes into these new scripts.

  1. Copy these scripts into your Assets/Scripts/ folder:
    1. Player.cs (updated)
    2. PlayerAnims.cs (updated)
    3. xa.cs (updated)
    4. ChangeBehaviorGUI.cs (new)
    5. Character.cs (new)
    6. Enemy.cs (new)
  2. Copy this script into your AstarPathfindingProject/Editor/GraphEditors folder:
    1. MyGridGeneratorEditor.cs
  3. And finally copy this script into your AstarPathfindingProject/Generators folder:
    1. MyGridGraph.cs

Configure The xa.cs Script

Create a new Layer by going to Edit –> Project Settings –> Tags and then enter “Enemy” in one of the empty User Layer slots.

  1. Select the Global/Scripts/xa GameObject
  2. Set Ground Mask field to “Ground
  3. Set Ladder and Rope Mask field to “NoDraw
  4. Set Enemy Mask field to “Enemy

Miscellaneous Project Changes

Note that some of these may be unnecessary or redundant depending on how your project is currently setup.

  1. Expand the Global game object in the Hierarchy and then select the “border bottom” and “border top” GameObjects and set their layer to Ground.  This is so enemies can stand on it if/when we dig a trap above the bottom border and our enemies fall into it they won’t fall continue through the border into the great abyss.
  2. Select the player object in the Hierarchy and then change its Tag to “Player
  3. Select the OT/View object in the Hierarchy and uncheck “Always Pixel Perfect“. Note I’m not sure why Adrian turns off pixel perfect, feel free experiment on your own.

Configure A* Pathfinding For Our Level

A* is a graph traversal algorithm widely used in computer science, and commonly used in games for path finding.  A full discussion of A* is beyond the scope of this tutorial, but there is some terminology you should be aware of.  A graph consists of nodes and the network of connections between them.  Once A* has been provided with a graph, you can query it to find the shortest path from one node to another.  A* will return a path way list of all the nodes that you must travel along to get from your start node to your end node, in the shortest path possible.  

More accurately, the path returned is the “least cost” path, because nodes have a specified penalty cost for traveling along it.  A* will attempt to create a path which incurs the least cost.  The unit of a penalty is up to the application developer.  For example, in an isometric RTS game the terrain tiles would be nodes, with 8 connections per node (except for the boundary tiles).  We could have the penalty cost units be related to the time it takes to travel on it.   A swampy area might therefore have very high penalties on the nodes in it, while the grass land nodes surrounding the swamp have smaller penalties.  A computer-controlled tank which wants to get from one side of the swamp to the other may then plot a course around the swamp if it costs less, even though it is physically further (i.e. more tiles must be travelled, but the total travel duration is less) . Of course, it is up to us as the game developer to implement all the code to actually slow the tank down if/when it travels over swamps, A* is only the pathfinder.

We don’t make use of penalties in this game because traveling along ropes, ladders, the ground, and falling is all done at the same speed.  If gravity in our game was a useful non-lethal force (i.e. falling is faster than climbing and just as safe) then we can set node penalties so that A* would return a path where jumping off a platform would be a preferable shortcut to climbing down the ladder. If your game enforces lethal falls from great heights, then you would need additional logic.

A game could have multiple graphs, for use by the various units (ships have different travel behavior to an infantry man for example).  For this tutorial, we only need to create one graph.  In the graph one node will be created for every tile in a 2d grid-like layout.  Each node may have up to 4 connections (up, down, left, right).  Aron’s A* Project includes several different path graph generators, such as GridGraph, ListGraph, and NavMeshGraph.  The GridGraph is a suitable starting point for our game.

The node connections generated by the base GridGraph are always bidirectional (if it creates a connection from from node1 to node2 then it will also create a connection from node2 to node1) which is not necessarily what we want.  Bidirectional paths are fine for ladders, ropes, and the ground because you can go up and down a ladder, and both left-to-right and right-to-left on rope and ground.  The problem arises when you want to include fall lanes. A fall lane is a term I’ve made up for a vertical one-way path that you can only travel on by falling.  Fall lanes exist under the ropes (you can let go of a rope and fall) and off of cliff edges (you can run off a cliff and fall down to a lower platform).  Once on a fall-lane you can’t travel in any direction but down until you’ve hit bottom.  This is a uni-directional connection so the nodes on a fall lane only have one connection each: a connection to the node directly below it.  Other nodes in the level will have between 2 and 4 connections each.  

We could use the base GridGraph and not bother about having any fall lanes, it would just mean that our AI would not plan any paths that involve letting go of ropes or running off platforms.  In this scenario you could still have your AI let go of ropes in a “reactionary” manner i.e. if it’s already on the rope and see a player below it, it could let go.  You would do this will “special case” code in your enemy AI loop.  However, its important to understand this is different from forward planning a route which takes into account the ability to jump off ropes.  In order to that kind of path planning with A*, you need to provide that information in the graph, via the fall lane concept.  

I’ve created a new generator class called “MyGridGraph” which inherits from GridGraph and overrides the Scan() and IsValidConnection() functions.  Our new MyGridGraph class implements the fall lanes idea so let’s add it the scene.

  1. Select the A* GameObject
  2. Click the Graphs -> Add Graph button
    1. Add a new “My Grid Graph
    2. Width26 (these dimensions match our level)
    3. Depth20
    4. Node Size1
    5. Aspect Ratio1
    6. Center0, 0.3, 0.01 (y is 0.3 so that our nodes are centered in the middle of each tile (which we already previously aligned at 0.3), the z is 0.01 because the integer coordinates used for Aron’s A* node positions have a fixed precision of 0.01 and anything smaller than that would cause troubles.)
    7. Rotation-90, 0, 0 (rotate x because our grid is for a side-on view rather than the expected top-down view)
    8. Disable Cut Corners checkbox
    9. ConnectionsSix (we only need 4 connections per node up/down/left/right, but we don’t have that option)
    10. Disable Collision testing checkbox
    11. Disable Height testing checkbox
    12. Level LayersGround and NoDraw
    13. Scroll to the bottom and enable the Show Graphs checkbox then hit Scan

If it worked right you should now see the A* graph layout in your game/scene window (enable Gizmos) similar to the following image (click to see a larger version).

2dGamePt5 pathfinding

The red squares represent nodes that the AI can not travel on.  All the bricks should have a red node centered on them.  Much of the black “air” tiles should also have a red square gizmo.  The tiles without the red gizmos are the nodes the AI can travel on.  The blue line represents the connections between nodes. You should therefore see that the AI can travel along the surface of ground tiles, along ropes, and up and down ladders.  You should also see the vertical fall lanes under ropes and over the edge of a platform.  If you are very perceptive you will see that the blue lines come in 2 thicknesses.  A thick line means that the connection is bidirectional (the line gizmo was rendered twice, once each way, making it thicker).  A thin line represents a unidirectional connection.

Making Enemies

Our enemies and the player classes both derive from the Character class which implements the movement code.  In this way we can ensure that the enemies and player move with the same constraints to help prevent giving either an unfair advantage, and just general time-saving and efficiency.  The character class does have a movement speed variable, so we can give the enemies different movement speeds than the player, if desired.

Below we create 2 enemy game objects.  I’ve just reused the player sprite for them, and I’ve given each one a different tint so I can tell them apart (helpful during the development stage). If you create your own different enemy sprite go ahead and use it.

  1. Create an empty GameObject called Enemies to use as an organizational holder.
  2. Clone the player GameObject in the hierarchy and rename it to enemy-1.
  3. Drag the enemy-1 to child it under your Enemies GameObject.
  4. Drag the /AstarPathfindingProject/Core/Seeker.cs script onto your enemy-1.  The script’s defaults are fine.  Go ahead and break enemy-1’s connection to the player prefab when prompted.  The Seeker provides the enemy with the ability to use A* path finding.  It has gizmos which paint green lines representing the found path.
  5. Expand the enemy-1 GameObject to see it’s children.
  6. Delete the “shoot parent” child.
  7. Add an empty GameObject child under enemy-1 named “path target”.  Local Position 0,0,0 Local Scale 1,1,1. This will be a transform that the enemy script will move around to place on the desired target for our path finding AI.  Useful during debugging to see what it is targeting.
  8. Duplicate “path target” and rename to “tile bounds”.  Add a box collider to it, set to Trigger and centered at 0,0,1 and scale 1,1,1.  This is so that when we trap an enemy we can walk smoothly on top of it’s head as if it was ground.
  9. Select the enemy-1 game object and set its Layer to Enemy and apply to children.  Set its Tag toEnemy (leave children untagged).
  10. Expand the enemy-1 Player script component.  Drag the /Scripts/Enemy.cs script onto the Player Scriptfield to replace it with the Enemy script.
  11. The Enemy script has 3 slots that need to be filled: Player and Player Tr (drag the player gameobject to those slots), and Target (drag the path target gameobject to this slot).
  12. Expand the enemy-1 OTAnimatingSprite script.  Set the Material Reference slot to “tint”.  Set theTint Color to red (or your preference) to visually differentiate it from the player.
  13. Clone enemy-1 as enemy-2 and give it a green tint. (You may have to redo the Red tint on the other enemy due to an OT quirk).
  14. Drag the enemies to suitable spawn points in the scene.
  15. Optional: Select the Enemies root GameObject.  Drag the ChangeBehaviors.cs script onto it.  Set the Enemies array size to 2, and drag enemy-1 and enemy-2 into the slots.  This script will allow you to modify an enemy’s behavior on-the-fly via GUI between a “plain A* to Player” and a “Lode Runner-esque” behavior.  The A* to Player behavior simply follows the shortest path toward the player’s exact position.  The Lode Runner-esque behavior still uses A* but also tries to reimplement some of the reactionary quirks of the original game, especially with regards to ladder use.  See the Enemy.cs file for details.  You can disable/remove the ChangeBehaviors.cs script when you are done testing it out.

Conclusion

While the enemy AI is not a completely faithful recreation of the original, it is hoped that it will provide you with enough of an idea on how you can use and implement A* path finding in your own creations.

If you have any questions about the tutorial, please let us know in the comments below. Your support helps to keep these tutorial coming so be sure to follow us on Twitter and Facebook. This blog post is part ofiDevBlogADay, a collection of indie developers writing about their development experiences.

原创粉丝点击