Quantcast
Channel: Kodeco | High quality programming tutorials: iOS, Android, Swift, Kotlin, Unity, and more
Viewing all articles
Browse latest Browse all 4370

Unreal Engine Tutorial for Beginners: Part 2

$
0
0
BlueprintMan: The hero of your game.

BlueprintMan: The hero of your game.

Welcome to the second part of this two-part tutorial series on Unreal Engine!

In the first part of this series, you learned the basics of Unreal Editor and the Blueprints visual scripting language. In this second and final part of the series, you’ll learn how to add loot and randomly spawn it in your game.

Getting Started

If you completed the previous part of this tutorial series, you can pick up where you left off. If you just want to get right into it, or want to start afresh, you can download the completed project from Part 1 and pick up from there.

Open your project in Unreal Editor; you’ll most likely see the following screen, depending on where you left off from Part 1 of the series:

Part2FirstLaunch

Click the 2DSideScrollerMap tab at the top left to navigate back to the main editor view:

Part2BackOnMainEditorScreen

Now you’re in position to start adding some loot to your game.

Creating and Animating Loot

As any good game designer knows, loot is an essential part of a 2D side-scrolling platformer. Otherwise, what’s the point of all that running and jumping around?

ragecomic_piratelootkpi

Yes, as any Pirate knows, the best loot of all is gold coins. Before you add the loot to your game, you’ll need some art assets to represent the loot in your game. Download the art assets file GoldCoins.zip generously donated by GameArtGuppy.com, and extract it to a convenient location.

In the content browser, navigate to the Sprites folder by right-clicking on the arrow between 2DSideScrollerBP and Blueprints, like so:

GoingToSprites

Left-click on Add New\New Folder to add a new folder:

CreateNewFolderSmall

Click on the new folder and edit its name to be Coins:

CoinsFolderSelectedSmall

Double-click Coins to navigate to the folder:

CoinsReadyToAdd

Right-click where it says Drop files here or right click to create content and click on the Import to /Game/… menu item:

CoinImagesImportMenu

This presents the import file dialog. Navigate to the GoldCoins directory you downloaded earlier, select all six coins as below, then click Open:

CoinImagesOpenSelected

You’ll probably see the warning shown below about non-powers of two; you can ignore this for now and simply click Yes:

CoinWarningCloseup

Once your import completes, you’ll see the six coin images inserted into your Coins folder and highlighted as below:

CoinImagesAdded

With the six coin images still selected, right-click on any of the images and choose Sprite Actions\Create Sprite:

CoinSpritesCreateFromImagesSmall

This creates coin sprites from each of the six coin images:

CoinSpritesAdded

Your coin sprites can now be drawn on-screen in your game. Much like Sprite Kit, Cocos2D and Unity, Unreal uses sprites to draw 2D images.

Look closely at the six sprites and observe how they appear to be drawn at different angles and in different states. That’s intentional: these sprites make up six different frames of a spinning coin animation. In order to create the animation, you need to place the sprites inside a Flipbook, which plays a sequence of sprites one after another.

With the six coin sprites still selected, right-click on any of them and select Create Flipbook:

CoinFlipbookCreateFromSpritesSmall

Click on your new flipbook and edit its name to be CoinFlipbook:

CoinFlipbookNaming

Double-click on CoinFlipbook to open the flipbook editor:

CoinFlipbookAt15fps

You’ll see your coin spinning smoothly around like so:

CoinsToFast

Congratulations: you’ve created your first Unreal animation! However, it would look a little better if the coin spun a little more slowly. Right now, the coin spins at the default animation rate of 15 fps. Edit Frames Per Second and reduce its value to 6 as shown below:

CoinFlipbookAt6fpsSmallWithLoupe

Check out the resulting slower animation:

CoinsToBetterSpeed

That looks a little less frantic.

Return to the 2DSideScrollerMap by clicking the tab at the top left. Then click the arrow between 2DSideScrollerBP and Sprites and select the Blueprints menu item:

CoinFlipbookGoingToBlueprintsFolder

If you were in Sprite Kit, you might add a Coin Class to model your coin loot in the game world. However, in Unreal, you’ll add a Coin Blueprint to model your coin. Click Add New\Blueprint Class to create a new Blueprint:

CoinBPAddBPMenuSmall

Next, click on Actor:

CoinBPMakeItAnActor

As the description says, an Actor is an object that can be placed and spawned in your game world. Your BlueprintMan character is an actor and your coins are also going to be actors.

Click on the Blueprint you just added:

CoinBPAdding

Edit its name to be CoinBP:

CoinBPAddedAndSelected

Note: It’s common convention in Unreal to name your Blueprints ending in BP as in CoinBP (or BP_Coin according to the Unreal Assets Naming Convention).

Double-click on CoinBP to launch the Blueprint editor for your coin:

CoinBPEditor

Click Add Component, type “flipbook” then press the down arrow and hit Enter to create your flipbook:

CoinBPAddingFlipbookComponentWithMisdrawnMenuSmall

Note:The Add Component menu seems to have some rendering bugs on OS X so you may see a blurry image like above.

You can leave the name as its default, PaperFlipbook:

CoinBPAddingFlipbookComponentSmall

Left-click on Sprite\Source Flipbook and select the CoinFlipbook you just created:

CoinBPSelectingFlipbookSmall

This will produce a sprite flipbook as shown below:

CoinFlipbookAddedToBP

Click Play and play your game; hey, weren’t you promised loot in your game? Oh right — you have to add your gold coin actors to the game first! Whoops. :]

Click Stop and return to the 2DSideScrollerExampleMap tab like so:

ReturnToMainEditorMap

The act of creating an instance of a Blueprint and adding it to the game world is called spawning. In Sprite Kit, you’d construct an instance of your Coin Class and add it to your game’s scene; the process in Unreal is somewhat similar.

Spawn Points: Make Your Loot Appear

You know what you want to spawn: your CoinBP Blueprint. Now you need to specify where you want to spawn it. These locations are called Spawn Points or Target Points.

One of the really neat things about Unreal is that you can edit your game world using drag-and-drop actions. In order to create a spawn point, there’s no need to calculate x and y coordinates; you simply create a spawn point by clicking on the desired location with your mouse.

In the Modes view, type target into the search box:

TargetPointModes

Target Point is Unreal’s name for Spawn Point; you’ll see then used interchangeably in the Unreal development universe.

Use your mouse to drag and drop the Target Point from the Modes view to the center viewport and place it as shown below:

SpawnPoint1TargetAdded

That was easy — you’ve created your first Spawn Point!

Note: Your CoinBP is an example of a Class Blueprint: a tightly-focused chunk of game logic that represents a single piece of functionality in your game — in this case, loot.

The other major kind of Blueprint in Unreal is known as the Level Blueprint. This is a Blueprint that controls high-level logic across the entire game level itself, and typically holds the spawn logic of your game.

Left-click Blueprints\Open Level Blueprint to open the Level Blueprint editor:

OpenLevelBlueprint

You’re going to create a function to spawn coins. Even though Blueprints is a visual scripting language, it uses familiar concepts like functions to organize bits of related logic just like lower-level code SDKs do.

Left-click the + in Functions under My Blueprint and set the name to SpawnCoin:

SpawnCoinAddedNewFunction

Your goal is to have SpawnCoin call a built-in event to spawn an actor (the coin) at a certain point (the target point you added earlier). For this to work, you need to add a reference to the target point you added earlier in your graph.

To do this, click on 2DSideScrollerExampleMap to bring up the main editor view and ensure that TargetPoint is selected in the World Outliner:

SpawnCoinWorldOutlinerTargetPointSelectedSmall

Click on your level blueprint editor again to return to it.

Note: You’ll see two tabs labelled 2DSideScrollerExampleMap: one is the actual level map and one is the level Blueprint editor.

Hover your mouse over the tabs and the tooltip will tell you which is the level Blueprint editor: it should say 2DSideScrollerExampleMap – Level Blueprint Editor.

Right-click on the graph and the context menu should appear as below:

SpawnCoinTargetPointReferenceContextMenuSmall

If, for some reason, the Create a Reference to TargetPoint doesn’t appear, make sure the Context Sensitive checkbox is checked; also check to make sure you selected TargetPoint in the World Outliner above.

Click Create a Reference to TargetPoint to add the reference point:

SpawnCoinTargetPointReferenceAddedSmall

Now you’ve created a placeholder for your Target Point that you can use within this graph’s logic.

Left-click on the Target Point node’s right output pin, drag out into the graph and release. Type get actor transform into the search box and press Enter:

SpawnCoinGetActorTransformSmall

You should see the following appear in your graph:

SpawnCoinGetActorTransformAddedSmall

You’re probably wondering “What’s an Actor Transform?”

The Actor is the object in this case — your target point — and the Actor Transform is your Actor’s set of 3D geometric properties: location, rotation and scale. Your Get Actor Transform node spawns your coin at the transform of your TargetPoint.

Left-drag from the right orange Return Value pin of the of the Get Actor Transform node into your graph. Type spawn in the resulting search box:

SpawnCoinSpawnActorFromClassContextMenuSmall

Select Spawn Actor from Class to create a new node:

SpawnCoinSpawnActorFromClassAddedSmall

Note that the Spawn Transform input pin of SpawnActor NONE is connected to the Return Value output pin of Get Actor Transform. You’ve created a piece of logic that says “use the location of the target point to set the location of the actor I’m spawning.” Now you just need to tell Unreal what to spawn at that location.

Click in the purple Class pin on the left of SpawnActor NONE and scroll down to CoinBP:

SpawnCoinSpawnActorFromClassSelectClassSmall

Release your mouse to set the class as follows:

SpawnCoinSpawnActorFromClassClassSelectedSmall

Note that the Class is now CoinBP and SpawnActor NONE is now SpawnActor CoinBP, indicating that the SpawnActor node is configured to spawn a CoinBP actor.

There’s one step left to complete your function: to trigger the spawn event when the function executes. Left-drag from the SpawnCoin output exec pin to the input exec pin of SpawnActor CoinBP, which will produce the following in your graph:

SpawnCoinFunctionHookedUpToSpawnActorFromClassSmall

That’s it — you’ve created your first Blueprint function. Well done! :] Now you need to wire up your function so you can invoke it during gameplay.

The wiring happens in your Level Blueprint’s EventGraph, since this is where the magic happens for events in your game. Click on the Event Graph tab:

BackToLevelBPEventGraph

You’re going to wire the L key to generate Loot. Right-click in the graph, type L into the search box and press Enter to create an L key event. Left-drag from the Pressed output pin and release in the graph. Type function in the search box and select Spawn Coin as shown below:

SpawnCoinConnectToLKeySmall

This produces the following:

LToSpawn

As a reward for all your hard work, you are now at a spot where you can test out your loot generation! Click the Play button and move your BlueprintMan so that he drops down to the lower left ledge near your target point. Press the L key to make a coin appear at the target point:

CoinAlwaysSpawnedAtFirstTarget

Cha-ching — show me the money! :] When you’re done admiring your shiny new loot, click the Stop button or press Esc to stop the gameplay.

Randomness: More Fun and More Repeat Plays

Your game would a lot more fun — and challenging — if your loot appeared randomly throughout your game world. There’s a term for this: variable ratio rewards, which means “when stuff happens randomly, it’s more fun and encourages repeat play of your game.” It turns out random generation like this is quite easy to achieve in Unreal.

Go back to the 2DSideScrollerExampleMap tab, drag another Target Point onto your viewport and drop it on the ledge just to the right of your first target point. This new target point will automatically be named TargetPoint2.

Return to the Level Blueprint, right-click in the graph and select Create a Reference to TargetPoint2.

Return to 2DSideScrollerExampleMap and add a third target point on the ledge just to the right of TargetPoint2, like so:

ThreeSpawnPointsAddedSmall

Unreal will automatically name this TargetPoint3.

Return to the Level Blueprint editor and add a reference to TargetPoint3. Your graph should now look like the following:

SpawnCoinTargetPoint2AddedSmall

To make random selection of target points easier, you’re going to add the three points to an array. Once again, Blueprints uses a familiar programming concept — arrays — to help you organize your game logic.

Right-click in the graph and type make array:

SpawnCoinArrayAddContextMenuSmall

Hit Enter to produce the following:

SpawnCoinArrayAddedSmall

Click the white + sign beside Add pin two times to produce a three-element array container:

SpawnCoinArrayPinsAddedSmall

Don’t worry about the red ERROR! message at the bottom of the node: this is just Unreal telling you that it doesn’t yet know what type of object is going to go in the array.

Left-drag from TargetPoint to the Make Array [0] pin; then perform the same action for TargetPoint2 and TargetPoint3 to the [1] and [2] pins respectively.

You’ll now have the following connections in place:

SpawnCoinArrayErrorReasonSmall

The error message is still there; simply click the Compile button to resolve the issues:

SpawnCoinArrayErrorClearedAfterCompileSmall

There, that looks better.

To spawn a coin, you need to randomly pick one element of your array. Right-click to the right of the array node, type array and select Get:

SpawnCoinArrayGetContextMenuSmall

Then left-drag from the left grid-like blue pin of the Get node to the right grid-like blue pin of the Make Array node to produce the following connection:

SpawnCoinIndex0AttachedToArraySmall

Left-drag from the right output blue pin of the Get node to the left input blue Target pin of the Get Actor Transform like so:

HookedUpToTarget

Note that the direct link from Get Actor Transform to TargetPoint has been replaced by this new link to the array, indicating that instead of hard-coding the value to a single spawn point, it should now choose an element from the array.

You’re almost there! Now you need to add some randomness.

ragecomic_dice

Left-drag from the green input pin of the Get node to create a Random Integer node and set its Max value to 3 as shown below:

SpawnCoinCompleteSmall

Since three-sided dice are hard (but not impossible!) to come by, you simply sample a random integer in 0, 1, 2 and use it as the index of the spawn point.

Click Play, drop down onto the lower ledges and press the L key a few times; you should see coins spawn randomly between your three spawn points. Click Stop when you’re done.

Right now, your game lets the player spawn a gold coin whenever they wish — predictable, but boring. It would be far more awesome if you could not only spawn the coins in random places, but at random times as well!

More Challenging Loot

Switch to the Event Graph tab in your Blueprint, right-click on an empty space, type event begin play and select the top match (Event Begin Play):

TimerEventBeginPlayContextMenu

You’ll be rewarded with the following:

TimerEventBeginPlayAddedSmall

EventBeginPlay occurs for any Blueprint when its life begins within the game; think of it as a post-initialization step that you can use to perform further setup tasks for your Blueprint. You’re going to wire up periodic coin spawning to begin when the level starts.

Left-drag from the EventBeginPlay right output pin and release in the graph. Type set timer in the search box:

TimerContextMenuSmall

Hit Enter to produce the following node:

TimerJustAddedSmall

Generating a coins every two seconds sounds just about right. Enter 2 in the Time pin and check the Looping pin to produce the following:

TimerTimeAndLoopingSetSmall

Type SpawnCoin (not that there is no space between “Spawn” and “Coin”) in the Function Name pin:

FunctionNameSet

This instructs Unreal to invoke the SpawnCoin function every two seconds and to continue doing so as long as the game keeps playing.

Click Play and you should see coins randomly spawn at one of the three spawn points, every two seconds, as shown below:

RandomLootSpawning

And there you have it — a solid start to a 2D platformer game — without writing a stitch of code. Neat, eh? :]

Where to Go From Here?

You can download the completed example project for this tutorial series here.

This tutorial has only scratched the surface of what you can do with Unreal; hopefully this series has piqued your interest to explore further.

You can find lots of additional documentation and tutorials on Unreal at the Epic games website; here are a few choice links that will give you some more in-depth information on what you’ve covered in this tutorial series:

If you enjoyed this tutorial and would like to see more Unreal Engine tutorials on this site, or if you have any questions or comments, please let us know in the comments below!

Unreal Engine Tutorial for Beginners: Part 2 is a post from: Ray Wenderlich

The post Unreal Engine Tutorial for Beginners: Part 2 appeared first on Ray Wenderlich.


Viewing all articles
Browse latest Browse all 4370

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>