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

GameplayKit Tutorial: Entity-Component System, Agents, Goals, and Behaviors

$
0
0
Note: This is a brand new tutorial released as part of the iOS 9 Feast. Enjoy!

Thumb

GameplayKit is a brand new framework introduced in iOS 9 that makes implementing many common tasks in your game much easier.

There are several different parts of GameplayKit, such as support for pathfinding, randomization, state machines, rule systems, and more.

In this GameplayKit tutorial, you’re going to focus on two parts of GameplayKit: its Entity-Component system, and Agents, Goals, and Behaviors.

These parts of GameplayKit help you organize your code in a different way that allows for more clean organization and code reuse, especially as your games become larger and larger.

Let’s dive in!

Introducing MonsterWars

In this GameplayKit tutorial, you will be working on a simple game called MonsterWars. Download the starter project, open it in Xcode, and build and run to check it out. You’ll see something like the following:

000_Starter

Right now, this game is just a shell with the UI elements added, but no gameplay. Here’s how the game will eventually work:

  • You’ll get money every so often, which you can see in the upper left. You can use it to buy units, by tapping the buttons at the bottom.
  • There are three enemy types: Quirk (fast and cheap), Zap (ranged attackers), and Munch (slow but has AOE chomp).
  • If your units destroy the enemy’s castle, you win!

Take a look at the code to see what’s there. Once you feel comfortable, read on to learn more about the main subject of this GameplayKit tutorial: its Entity-Component system.

Why Do We Need an Entity-Component System?

When you’re making a game, you need to create objects to represent the entities in your games – like monsters, the player, bullets, and so on.

When you first get started, you might think the most logical thing is to create a base class called “Game Object” that contains the common code. Then you can create subclasses for Monsters, and maybe subclasses of Monsters for specific types of monsters.

For simple games, this works quite fine and is quite easy to program. However, as your game get larger and more complex, this architecture begins to cause some problems in practice.

For example – imagine you decided to implement MonsterWars with the following oriented architecture:

Inheritance based architecture

Here the Player class represents the castles on either side, and the Monster class represents the monsters, and has subclasses for each type of monsters. Monsters can have either ranged or melee attacks.

But what happens if you want to make the castles shoot? All of that code is in the Monster class instead of the Player class. That means you have two options:

  1. Rework the object hierarchy. You could switch around the object hierarchy – maybe make Player a subclass of Monster.
  2. Move the code to a common base class. Alternatively you could move the ranged properties and code up to a common base class. The common base class of Monster and Player is GameObject.

Both of these options are equally bad. This kind of thing happens a lot as you make your game, and before long you have one massive spaghetti class filled with code. That’s with the Entity-Component system is designed to solve!

What is an Entity-Component System?

There are two parts of an entity component system:

  • Components: You make small components for each type of thing your game objects can do. For example, you might make a melee attack component, a ranged attack component, a health component, a movement component, and so on.
  • Entities: Since you moved all of your game logic to small independent components, now your entities can just be a collection of components configured a certain way. For example, you can add a batch of components together to make a zap monster.

The easiest way to see how this works is to try it out. So enough theory for now – it’s time to dive in!

Note: If you’re still itching for more on the theory side, check out this old tutorial I wrote several years ago where I rolled an entity-component system from scratch and compare it to a few other approaches.

Your First Component

To get started, let’s create a component to represent a sprite on the screen. To do this in GameplayKit, you make a subclass of GKComponent.

To do this, select your MonsterWars group in the Project Navigator, right click, select New Group, and name the group Components.

Then right click the Components group, select New File.., select the iOS\Source\Swift File template, and click Next. Name the new file SpriteComponent.swift and click Create.

At this point, your project navigator should look like this:

001_First_Component

Open SpriteComponent.swift and replace the contents with the following:

// 1
import SpriteKit
import GameplayKit
 
// 2
class SpriteComponent: GKComponent {
 
  // 3
  let node: SKSpriteNode
 
  // 4
  init(texture: SKTexture) {
    node = SKSpriteNode(texture: texture, color: SKColor.whiteColor(), size: texture.size())
  }
}

Let’s review this section by section:

  1. To use GameplayKit, you must import it just like you do for SpriteKit.
  2. To create a GameplayKit component, simply subclass GKComponent.
  3. This component will keep track of a sprite, so you declare a property for one here.
  4. This is a simple initializer that initializes the sprite based on a texture you pass in.

Your First Entity

In GameplayKit, GKEntity is the class that represents an entity. You can add components to it, like the one you just created.

In my opinion, it’s often helpful to create a subclass of GKEntity for each type of object that you add to the game. In this game for example, there are five types of objects: castles, quirk monsters, zap monsters, munch monsters, and lasers.

Your GKEntity subclass should be very simple, and usually just an initializer that adds the types of components you typically need for that type of object. It’s best not to have much more code than that in the entity; leave that to the components!

Let’s create an entity the castles. To do this, select your MonsterWars group in the Project Navigator, right click, select New Group, and name the group Entities.

Then right click the Entities group, select New File.., select the iOS\Source\Swift File template, and click Next. Name the new file Castle.swift and click Create.

At this point, your project navigator should look like this:

002_First_Entity

Open Castle.swift and replace the contents with the following:

import SpriteKit
import GameplayKit
 
// 1
class Castle: GKEntity {
 
  init(imageName: String) {
    super.init()
 
    // 2
    let spriteComponent = SpriteComponent(texture: SKTexture(imageNamed: imageName))
    addComponent(spriteComponent)
  }
}

There are just two things to point out here:

  1. As I mentioned earlier, it’s often convenient to subclass GKEntity for each type of object in your game. The alternative is to create a base GKEntity and dynamically add the types of components you need; but often you want to have a “cookie cutter” for a particular type of object. That is what this is!
  2. At this point, you add just one component to the entity – the sprite component you just created. You’ll be adding more components to this entity soon!

Now that you’ve created a component and an entity, you’re almost ready to add it into the game. But first, we need to create a helper class to help manage our entities.

The Entity Manager

In this section, you’re going to create a helper class to manage the entities you add to your game. It will keep a list of all the entities in the game, and have some helper methods for things like adding and removing entities.

Right-click your Entities group, select New File.., select the iOS\Source\Swift File template, and click Next. Name the new file EntityManager.swift and click Create.

Open EntityManager.swift and replace the contents with the following:

import Foundation
import SpriteKit
import GameplayKit
 
class EntityManager {
 
  // 1
  var entities = Set<GKEntity>()
  let scene: SKScene
 
  // 2
  init(scene: SKScene) {
    self.scene = scene
  }
 
  // 3
  func add(entity: GKEntity) {
    entities.insert(entity)
 
    if let spriteNode = entity.componentForClass(SpriteComponent.self)?.node {
      scene.addChild(spriteNode)
    }
  }
 
  // 4
  func remove(entity: GKEntity) {
    if let spriteNode = entity.componentForClass(SpriteComponent.self)?.node {
      spriteNode.removeFromParent()
    }
 
    entities.remove(entity)
  }
}

Let’s review this section by section:

  1. This class will keep a reference to all entities in the game, along with the scene.
  2. This is a simple initializer that stores the scene in the property you created.
  3. This is a helper function that you will call when you want to add an entity to your game. It adds it to the list of entities, and then check to see if the entity has a SpriteComponent. If it does, it adds the sprite’s node to the scene.
  4. This is a helper function that you will call when you want to remove an entity from your game. This does the opposite of the add(_:) method; if the entity has a SpriteComponent, it removes the node from the scene, and it also removes the entity from the list of entities.

You’ll be adding more methods to this helper class in the future, but this is a good start for now. First let’s get something showing up on the screen!

Adding Your Castles

Open GameScene.swift and add this property to the bottom of your list of properties:

var entityManager: EntityManager!

This is to store an instance of the helper class you just created.

Next add this code to the bottom of didMoveToView(_:):

// 1
entityManager = EntityManager(scene: self)
 
// 2
let humanCastle = Castle(imageName: "castle1_atk")
if let spriteComponent = humanCastle.componentForClass(SpriteComponent.self) {
  spriteComponent.node.position = CGPoint(x: spriteComponent.node.size.width/2, y: size.height/2)
}
entityManager.add(humanCastle)
 
// 3
let aiCastle = Castle(imageName: "castle2_atk")
if let spriteComponent = aiCastle.componentForClass(SpriteComponent.self) {
  spriteComponent.node.position = CGPoint(x: size.width - spriteComponent.node.size.width/2, y: size.height/2)
}
entityManager.add(aiCastle)

Let’s review this section by section:

  1. Creates an instance of the EntityManager helper class you created in the previous section.
  2. Creates an instance of your Castle entity you created earlier to represent the human player. After creating the castle it retrieves the sprite component and positions it on the left hand side of the screen. Finally, it adds it to the entity manager.
  3. Similar code to set up the AI player’s castle.

That’s it! Build and run and you’ll see your castles in the game:

003_Castles

Your Second Component

When you develop games with an entity-component system, all data that you need for your game objects must be stored in some kind of component.

One thing that you’ll need for this game is to keep track of which team an object belongs to – team 1 or team 2. That information doesn’t belong on your Sprite Component; you might want to have an entity that doesn’t belong to either team for example. Therefore, let’s create a new component for that.

Right-click your Components group, select New File.., select the iOS\Source\Swift File template, and click Next. Name the new file TeamComponent.swift and click Create.

Open TeamComponent.swift and replace the contents with the following:

import SpriteKit
import GameplayKit
 
// 1
enum Team: Int {
  case Team1 = 1
  case Team2 = 2
 
  static let allValues = [Team1, Team2]
 
  func oppositeTeam() -> Team {
    switch self {
      case .Team1:
        return .Team2
      case .Team2:
        return .Team1
    }
  }
}
 
// 2
class TeamComponent: GKComponent {
  let team: Team
 
  init(team: Team) {
    self.team = team
    super.init()
  }
}

This is a fairly simple file, so I’ll just point out two things:

  1. This is an enumeration to keep track of the two teams in this game – team 1 and team 2. It also has a helper method to return the opposite team, which will come in handy later.
  2. This is a very simple component that simply keeps track of the team for this entity.

Now that you have this new component, let’s update your castle entity to use it. Open Castle.swift and modify the initializer to take the team as a parameter:

init(imageName: String, team: Team) {

Then add this line to the bottom of init(_:team:):

addComponent(TeamComponent(team: team))

This adds your new component to the castle entity. Finally, open GameScene.swift and replace the line that initializes humanCastle with the following:

let humanCastle = Castle(imageName: "castle1_atk", team: .Team1)

Similarly, replace the line that initializes aiCastle with the following:

let aiCastle = Castle(imageName: "castle2_atk", team: .Team2)

Build and run the game. You shouldn’t notice any changes, but you have now successfully associated a new set of data to your entity which will come in handy later.

Your Third Component

Another piece of data you need to keep track of is each player’s current coins. In this game, since there’s a single castle on each side, you’ll think of the castle as the “commander” for each player and it will be a good place to store this information.

So let’s create a CastleComponent that will store this. Right-click your Components group, select New File.., select the iOS\Source\Swift File template, and click Next. Name the new file CastleComponent.swift and click Create.

Open CastleComponent.swift and replace the contents with the following:

import SpriteKit
import GameplayKit
 
class CastleComponent: GKComponent {  
 
  // 1
  var coins = 0
  var lastCoinDrop = NSTimeInterval(0)
 
  override init() {
    super.init()
  }
 
  // 2
  override func updateWithDeltaTime(seconds: NSTimeInterval) {
 
    super.updateWithDeltaTime(seconds)
 
    // 3
    let coinDropInterval = NSTimeInterval(0.5)
    let coinsPerInterval = 10
    if (CACurrentMediaTime() - lastCoinDrop > coinDropInterval) {
      lastCoinDrop = CACurrentMediaTime()
      coins += coinsPerInterval
    }
  }
}

This component is a little different than the others, so let’s review this in more detail.

  1. This stores the number of coins in the castle, and the last time coins were earned.
  2. This method will be called on each frame of the game. Note this is not called by default; you have to do a little bit of setup to get this to happen, which you’ll do shortly.
  3. This is a bit of code to spawn coins periodically.

Like you did before, you need to add this new component to your Castle entity. To do this, open Castle.swift and add this to the bottom of init(_:team:):

addComponent(CastleComponent())

Next, you need to add the code I mentioned earlier to get your updateWithDeltaTime(_:) method to be called. To do this, open EntityManager.swift and add this new property to the top of the class:

lazy var componentSystems: [GKComponentSystem] = {
  let castleSystem = GKComponentSystem(componentClass: CastleComponent.self)
  return [castleSystem]
}()

Think of GKComponentSystem as a class that stores a collection of components. Here, you create a GKComponentSystem to keep track of all of the CastleComponent instances in your game.

You then put the GKComponentSystem that stores component systems into an array. Right now it’s the only thing in the array, but you’ll be adding more to this later.

You’ll see the purpose behind doing this soon.

First, add this to the end of add(_:):

for componentSystem in componentSystems {
  componentSystem.addComponentWithEntity(entity)
}

Here whenever you add a new entity, you add it to each of the component systems in your array (right now, it only contains the castle component system). Don’t worry – if your entity does not contain a castle component, nothing will happen.

Next, add this to the end of remove(_:):

toRemove.insert(entity)

Note that instead of removing the entity directly from the component system, you add it to a toRemove set, so you can remove it later. This is because later in this tutorial you will end up in a situation where you want to remove an entity while you are enumerating the objects in a component system, and in Swift you cannot modify a collection while you are iterating it.

The compiler will complain that the toRemove set does not exist, so add this property to the top of the class:

var toRemove = Set<GKEntity>()

Finally, add this new method to the bottom of the class:

func update(deltaTime: CFTimeInterval) {
  // 1
  for componentSystem in componentSystems {
    componentSystem.updateWithDeltaTime(deltaTime)
  }
 
  // 2
  for curRemove in toRemove {
    for componentSystem in componentSystems {
      componentSystem.removeComponentWithEntity(curRemove)
    }
  }
  toRemove.removeAll()
}

Let’s review this section by section:

  1. Here you loop through all the component systems in the array and call updateWithDeltaTime(_:) on each one. This causes each component system to call updateWithDeltaTime(_:) on each component in their system in turn.

    This actually demonstrates the whole purpose and benefit of using GKComponentSystem. The way this is set up, components are updated one system at a time. In games, it’s often convenient to have precise control over the ordering of the processing of each system (physics, rendering, etc).

  2. Here you loop through anything in the toRemove array and remove those entities from the component systems.

There’s one last helper method to add to this file. Add this method to the bottom of the class:

func castleForTeam(team: Team) -> GKEntity? {
  for entity in entities {
    if let teamComponent = entity.componentForClass(TeamComponent.self),
           _ = entity.componentForClass(CastleComponent.self) {
      if teamComponent.team == team {
        return entity
      }
    }
  }
  return nil
}

This is a helper method that loops through all of the entities in the game, and looks to see any entities that have both a TeamComponent and a CastleComponent – which should be the two castles in the game. It then checks to see if the team matches the passed in parameter, and then returns that.

Basically, this is a handy method to get the castle for a particular team.

Note: An alternative way of doing this would have been to just keep a reference to the castle entity when you make it. The advantage of looking up things dynamically like this is your game is more flexible. Although you probably don’t need the flexibility in this case, I wanted to show this to you because in many games this flexibility is quite handy, and in fact the main benefit of the entity-component system architecture in the first place.

Let’s hook this up to the game scene now. Open GameScene.swift and add this code to the bottom of update(_:):

entityManager.update(deltaTime)
 
if let human = entityManager.castleForTeam(.Team1),
       humanCastle = human.componentForClass(CastleComponent.self) {
  coin1Label.text = "\(humanCastle.coins)"
}
if let ai = entityManager.castleForTeam(.Team2),
       aiCastle = ai.componentForClass(CastleComponent.self) {
  coin2Label.text = "\(aiCastle.coins)"
}

This calls the update(_:) method you just wrote on the entity manager. It then finds the castle (and castle component) for each team, and updates the labels with the current coin values from each component.

Build and run, and see the money begin to roll in!

004_Money

Your Second Entity

Next, let’s modify the game so you can spawn Quirk monsters. Of course, you’ll need a new entity for that to keep the “cookie cutter” configuration in one centralized spot.

Right-click your Entities group, select New File.., select the iOS\Source\Swift File template, and click Next. Name the new file Quirk.swift and click Create.

Open Quirk.swift and replace the contents with the following:

import SpriteKit
import GameplayKit
 
class Quirk: GKEntity {
 
  init(team: Team) {
    super.init()
    let texture = SKTexture(imageNamed: "quirk\(team.rawValue)")
    let spriteComponent = SpriteComponent(texture: texture)
    addComponent(spriteComponent)
    addComponent(TeamComponent(team: team))
  }
 
}

This is very similar to how you set up the castle entity and you should understand everything in this class at this point.

Now it’s time to create an instance of the Quirk entity. Last time, you created the Castle entity directly in GameScene, but this time you’ll move the code to spawn a Quick monster into EntityManager. It will be nice to have this in a centralized spot later.

To do this, open EntityManager.swift and add this method to the bottom of the class:

func spawnQuirk(team: Team) {
  // 1
  guard let teamEntity = castleForTeam(team),
        teamCastleComponent = teamEntity.componentForClass(CastleComponent.self),
        teamSpriteComponent = teamEntity.componentForClass(SpriteComponent.self) else {
    return
  }
 
  // 2
  if teamCastleComponent.coins < costQuirk {
    return
  }
  teamCastleComponent.coins -= costQuirk
  scene.runAction(SoundManager.sharedInstance.soundSpawn)
 
  // 3
  let monster = Quirk(team: team)
  if let spriteComponent = monster.componentForClass(SpriteComponent.self) {
    spriteComponent.node.position = CGPoint(x: teamSpriteComponent.node.position.x, y: CGFloat.random(min: scene.size.height * 0.25, max: scene.size.height * 0.75))
    spriteComponent.node.zPosition = 2
  }
  add(monster)
}

Let’s review this section by section:

  1. Monsters should be spawned near their team’s castle. To do this, you need the position of the castle’s sprite, so this is some code to look up that information in a dynamic way.
  2. This checks to see if there are enough coins to spawn the monster, and if so subtracts the appropriate coins and plays a sound.
  3. This is the code to create a Quick entity and position it near the castle (at a random y-value).

Finally, open GameScene.swift and add this to the end of quirkPressed():

entityManager.spawnQuirk(.Team1)

Build and run, and tap away to spawn some monsters!

005_Quirks

Agents, Goals, and Behaviors

So far, the quirk monsters are just sitting right there doing nothing. But that’s no good – this game needs movement!

Luckily, GameplayKit comes with a set of classes collectively known as “agents, goals, and behaviors” that makes moving objects in your game in complex ways super easy. Here’s how it works:

  • GKAgent2D is a subclass of GKComponent that handles moving objects in your game. You can set different properties on it like max speed, acceleration, and so on, and the GKBehavior to use.
  • GKBehavior is a class that contains a set of GKGoals, representing how you would like your objects to move.
  • GKGoal represents a movement goal you might have for your agents – for example to move toward another agent.

So basically, you configure these objects and add the GKAgent component to your class, and GameplayKit will move everything for you from there!

Note: There is one caveat: GKAgent2D doesn’t move your sprites directly, it just updates its own position appropriately. You need to write a bit of glue code to match up the sprite position with the GKAgent position.

Let’s try this out, starting by creating the behavior and goals. Right-click your Components group, select New File.., select the iOS\Source\Swift File template, and click Next. Name the new file MoveBehavior.swift and click Create.

Open MoveBehavior.swift and replace the contents with the following:

import GameplayKit
import SpriteKit
 
// 1
class MoveBehavior: GKBehavior {
 
  init(targetSpeed: Float, seek: GKAgent, avoid: [GKAgent]) {
    super.init()
    // 2
    if targetSpeed > 0 {
      // 3
      setWeight(0.1, forGoal: GKGoal(toReachTargetSpeed: targetSpeed))
      // 4
      setWeight(0.5, forGoal: GKGoal(toSeekAgent: seek))
      // 5
      setWeight(1.0, forGoal: GKGoal(toAvoidAgents: avoid, maxPredictionTime: 1.0))
    }
  }
}

There’s a lot of new stuff here, so let’s review this section by section:

  1. You create a GKBehavior subclass here so you can easily configure a set of movement goals.
  2. If the speed is less than 0, don’t set any goals as the agent should not move.
  3. To add a goal to your behavior, you use the setWeight(_:forGoal:) method. This allows you to specify a goal, along with a weight of how important it is – larger weight values take priority. In this instance, you set a low priority goal for the agent to reach the target speed.
  4. Here you set a medium priority goal for the agent to move toward another agent. You will use this to make your monsters move toward the closest enemy.
  5. Here you set a high priority goal to avoid colliding with a group of other agents. You will use this to make your monsters stay away from their allies so they are nicely spread out.

Now that you’ve created your behavior and goals, you can set up your agent. Right-click your Components group, select New File.., select the iOS\Source\Swift File template, and click Next. Name the new file MoveComponent.swift and click Create.

Open MoveComponent.swift and replace the contents with the following:

import SpriteKit
import GameplayKit
 
// 1
class MoveComponent : GKAgent2D, GKAgentDelegate {
 
  // 2
  let entityManager: EntityManager
 
  // 3
  init(maxSpeed: Float, maxAcceleration: Float, radius: Float, entityManager: EntityManager) {
    self.entityManager = entityManager
    super.init()
    delegate = self
    self.maxSpeed = maxSpeed
    self.maxAcceleration = maxAcceleration
    self.radius = radius
    print(self.mass)
    self.mass = 0.01
  }
 
  // 4
  func agentWillUpdate(agent: GKAgent) {
    guard let spriteComponent = entity?.componentForClass(SpriteComponent.self) else {
      return
    }
 
    position = float2(spriteComponent.node.position)
  }
 
  // 5
  func agentDidUpdate(agent: GKAgent) {
    guard let spriteComponent = entity?.componentForClass(SpriteComponent.self) else {
      return
    }
 
    spriteComponent.node.position = CGPoint(position)
  }
}

There’s lots of new stuff here as well, so let’s review this section by section:

  1. Remember that GKAgent2D is a subclass of GKComponent. You subclass it here so customize its functionality. Also, you implement GKAgentDelegate – this is how you’ll match up the position of the sprite with the agent’s position.
  2. You’ll need a reference to the entityManger so you can access the other entities in the game. For example, you need to know about your closest enemy (so you can seek to it) and your full list of allies (so you can spread apart from them).
  3. GKAgent2D has various properties like max speed, acceleration, and so on. Here you configure them based on passed in parameters. You also set this class as its own delegate, and make the mass very small so objects respond to direction changes more easily.
  4. Before the agent updates its position, you set the position of the agent to the sprite component’s position. This is so that agents will be positioned in the correct spot to start. Note there’s some funky conversions going on here – GameplayKit uses float2 instead of CGPoint, gah!
  5. Similarly, after the agent updates its position agentDidUpdate(_:) is called. You set the sprite’s position to match the agent’s position.

You still have a bit more to do in this file, but first you need to add some helper methods. Start by opening EntityManager.swift and add these new methods:

func entitiesForTeam(team: Team) -> [GKEntity] {  
  return entities.flatMap{ entity in
    if let teamComponent = entity.componentForClass(TeamComponent.self) {
      if teamComponent.team == team {
        return entity
      }
    }
    return nil
  }  
}
 
func moveComponentsForTeam(team: Team) -> [MoveComponent] {
  let entities = entitiesForTeam(team)
  var moveComponents = [MoveComponent]()
  for entity in entities {
    if let moveComponent = entity.componentForClass(MoveComponent.self) {
      moveComponents.append(moveComponent)
    }
  }
  return moveComponents
}

entitiesForTeam(_:) returns all entities for a particular team, and moveComponentsForTeam(_:) returns all move components for a particular team. You’ll need these shortly.

Switch back to MoveComponent.swift and add this new method:

func closestMoveComponentForTeam(team: Team) -> GKAgent2D? {
 
  var closestMoveComponent: MoveComponent? = nil
  var closestDistance = CGFloat(0)
 
  let enemyMoveComponents = entityManager.moveComponentsForTeam(team)
  for enemyMoveComponent in enemyMoveComponents {
    let distance = (CGPoint(enemyMoveComponent.position) - CGPoint(position)).length()
    if closestMoveComponent == nil || distance < closestDistance {
      closestMoveComponent = enemyMoveComponent
      closestDistance = distance
    }
  }
  return closestMoveComponent
 
}

This is some code to find the closest move component on a particular team from the current move component. You will use this to find the closest enemy now.

Add this new method to the bottom of the class:

override func updateWithDeltaTime(seconds: NSTimeInterval) {
 
  super.updateWithDeltaTime(seconds)
 
  // 1
  guard let entity = entity,
        let teamComponent = entity.componentForClass(TeamComponent.self) else {
    return
  }
 
  // 2
  guard let enemyMoveComponent = closestMoveComponentForTeam(teamComponent.team.oppositeTeam()) else {
    return
  }
 
  // 3
  let alliedMoveComponents = entityManager.moveComponentsForTeam(teamComponent.team)
 
  // 4
  behavior = MoveBehavior(targetSpeed: maxSpeed, seek: enemyMoveComponent, avoid: alliedMoveComponents)
 
}

This is the update loop that puts it all together.

  1. Here you find the team component for the current entity.
  2. Here you use the helper method you wrote to find the closest enemy.
  3. Here you use the helper method you wrote to find all your allies’s move components.
  4. Finally, you reset the behavior with the updated values.

Almost done; just a few cleanup items to do. Open EntityManager.swift and update the line that sets up the componentSystems property as follows:

lazy var componentSystems: [GKComponentSystem] = {
  let castleSystem = GKComponentSystem(componentClass: CastleComponent.self)
  let moveSystem = GKComponentSystem(componentClass: MoveComponent.self)
  return [castleSystem, moveSystem]
}()

Remember, this is necessary so that your updateWithDeltaTime(_:) method gets called on your new MoveComponent.

Next open Quirk.swift and modify your initializer to take the entityManager as a parameter:

init(team: Team, entityManager: EntityManager) {

Then add this to the bottom of init(_:entityManager:):

addComponent(MoveComponent(maxSpeed: 150, maxAcceleration: 5, radius: Float(texture.size().width * 0.3), entityManager: entityManager))

This creates your move component with some values that work well for the quick Quirk monster.

You need a move component for the castle too – this way they can be one of the agents considered for the “closest possible enemy”. To do this, open Castle.swift and modify your initializer to take the entityManager as a parameter:

init(imageName: String, team: Team, entityManager: EntityManager) {

Then add this to the bottom of init(_:team:entityManager:):

addComponent(MoveComponent(maxSpeed: 0, maxAcceleration: 0, radius: Float(spriteComponent.node.size.width / 2), entityManager: entityManager))

Finally, move to EntityManager.swift and inside spawnQuirk(_:), modify the line that creates the Quirk instance as follows:

let monster = Quirk(team: team, entityManager: self)

Also open GameScene.swift and modify the line in didMoveToView(_:) that creates the humanCastle:

let humanCastle = Castle(imageName: "castle1_atk", team: .Team1, entityManager: entityManager)

And similarly for aiCastle:

let aiCastle = Castle(imageName: "castle2_atk", team: .Team2, entityManager: entityManager)

Build and run, and enjoy your moving monsters:

006_MovingMonsters

Congratulations! At this point you have a good understanding of how to use the new Entity-Component system in GameplayKit, along with using Agents, Goals, and Behaviors for movement.

Where to Go From Here?

Here is the finished example project from this GameplayKit tutorial.

At this point, you can repeat the process described here to add more components to your game – for example a component to deal melee damage, a component to fire lasers, a component to display a health bar, etc.

I thought about extending the tutorial to show how to do all this, but this tutorial has gone on long enough. So instead, I created a project for the complete game that you can download and take a look at for reference.

If you want to learn more about GameplayKit, you should check out our book 2D iOS & tvOS Games by Tutorials:

In this book we’ll teach you everything you need to know to make great games for iOS & tvOS – from physics, to tile maps, to particle systems, and even how to make your games “juicy” with polish and special effects.

I hope you enjoyed this tutorial, and if you have any questions or comments, please join the forum discussion below!

The post GameplayKit Tutorial: Entity-Component System, Agents, Goals, and Behaviors appeared first on Ray Wenderlich.


iOS 9 Feast Giveaway Winners!

$
0
0

iOS 9 Feast

This past month has been the most incredible month we’ve ever had at raywenderlich.com.

During the iOS 9 Feast, we released:

  • 7 new books
  • 23 new written tutorials
  • 78 new video tutorials!

This represents a huge amount of work on behalf of our team, and I’m really proud of our authors, editors, and video instructors for putting this together.

But all good things must come to an end. And in the case of the iOS 9 Feast, we like to end things with a bang.

So today, we are pleased to announce the winners of our iOS 9 Feast giveaway! We have over $18,000 in value of prizes to give away – one grand prize winner, and 150 second prize winners.

Keep reading to see some pictures of the books released in the feast, to find out who the lucky winners are, how to claim your prize if you are a lucky winner, and how to get a second chance in case you aren’t! :]

Book Pictures!

Before we jump into the lucky winners, I wanted to share some pictures of what the books look like that we released during this year’s feast.

Here are the books all together:

AllBooksFull

If you stack them up, they’re over 7.5 inches of content!

AllBooksStack

But as John Blanco wisely said, “It’s not the size that matters, it’s how you peruse it.” :]

Here’s what the full collection of raywenderlich.com books over the years looks like:

Bookshelf

I don’t know what we’re gonna do next year – I’m running out of bookshelf space! :P

Again huge congratulations to all of the authors, editors, tech editors, and final pass editors for making these books – I’m really happy with how they turned out.

Full Prize List

Now for the main matter at hand!

Here’s the full list of prizes. The grand prize winner gets them all (is your mouth watering yet?):

iOS 9 Feast Giveaway!

Version Control Tools

  1. Tower 2 ($69 value): Version control with Git – made easy. In a beautiful, efficient, and powerful app.
  2. Gitbox ($15 value): Version control as easy as Mail: One-click commit, push and pull.

Continuous Integration

  1. Bitrise Lifetime Atlantis Subscription ($1545/year value): iOS Continuous Integration and Delivery for your whole team, with dozens of integrations for your favorite services.

App Localization

  1. Applanga 6 Month Pro Subscription ($330 value): Everything you need to make mobile app localization fast and easy.

iOS Controls

  1. ShinobiCharts ($395 value): Bring your app’s data to life with these professional chart components.
  2. ShinobiToolkit ($395 value): An excellent collection of UI controls to enhance your apps with features like Grids, Calendars, Carousels and Gauges.
  3. ShinobiForms ($199 value): Tools for building user input forms quickly and easily.

Other Development Tools

  1. Hopper ($89 value): A reverse engineering tool for OS X and Linux, that lets you disassemble, decompile and debug your 32/64bits Intel Mac, Linux, Windows and iOS executables.
  2. Reveal ($89 value) – A powerful runtime view debugging tool with advanced visualisations, comprehensive inspectors and the ability to modify applications on the fly.
  3. Paw (HTTP & REST Client) ($30 value): A handy app to test HTTP calls and RESTful APIs. It lets you send HTTP requests (like cURL), and generates NSURLConnection or AFNetworking code.
  4. Dash ($20 value): Instant offline access to documentation sets, and extremely handy snippet manager.

Design Tools

  1. Paint Code 2 ($100 value): PaintCode is a vector drawing app that generates Core Graphics code in real time.
  2. Core Animator ($100 value): Turn your own animations into native iOS code.
  3. Principle for Mac ($99 value): Principle makes it easy to create animated and interactive user interface designs!
  4. Zeplin 6-month Subscription ($90 value): A tool that makes handing off designs from designers to developers much easier. Generate styleguides, and resources, automatically!
  5. Affinity Photo ($50 value): Photo editing software that offers sophisticated tools for enhancing, editing and retouching your images in an incredibly intuitive interface.
  6. Affinity Designer ($50 value): The fastest, smoothest, most precise vector graphic design software available; great for creating graphics for marketing materials, websites, icons, UI design or even cool concept art.
  7. AppCooker ($30 value): Design apps like a chef – right on your iPad!
  8. Pixelmator ($30 value) – An inspiring, easy-to-use, beautifully designed image editor that lets you enhance photos, sketch, draw and paint, add text and shapes, apply dazzling effects, and more!
  9. Acorn 5 ($25 value): An easy to use Mac image editor, designed for humans. With a ton of new features and refinements, you will make beautiful images in Acorn!
  10. Astropad for iPad ($20 value): Turn your iPad into a graphics tablet!
  11. Astropad for iPhone ($5 value): Turn your iPhone into a graphics tablet!
  12. Promotee ($5 value): Make your app’s promo art shine using this tool to create slick framed product shots.

Productivity Tools

  1. Monodraw ($20 value): A neat tool for creating diagrams, layouts, and flow charts – in ASCII art! :]
  2. Reflector 2 ($15 value): Easily mirror your iPad, iPhone, or Android devices wherever you want it – your Mac, Apple TV, Google Cast, or even live on YouTube!
  3. Soulver ($12 value): A handy app to help you play around with numbers, more conveniently than a traditional calculator.

Blogging Tools

  1. WordPress.com Premium 1-year subscription ($99 value): Create a beautiful website to promote your app with the same awesome software we use for our blog.

Game Tools

  1. Particle Designer 2 ($80 value): Create amazing particle systems for your games with a visual editor designed specifically for Mac OS X.
  2. Glyph Designer 2 1-year Subscription ($53 value): Design beautiful fonts for your iOS games.
  3. TexturePacker ($49 value): The sprite sheet creator that turns chaos into order!
  4. PhysicsEditor ($49 value): Edit your physics shapes with ease!
  5. SpriteIlluminator ($49 value): Create and edit normal maps and add dynamic light to your 2D games.

Conference tickets

  1. 360iDev ($799 value): A free ticket to 360iDev 2016 – an awesome 4-day event for app developers!
  2. Swift Summit ($799 value): A free ticket to your choice of 2016 Swift Summit: A gathering of the world’s top Swift developers, bloggers, book authors and teachers.
  3. RWDevCon ($899 value): A free ticket to our official raywenderlich.com conference: Come meet the team for some great hands-on tutorials, inspiration, and fun!

Books

  1. Swift Apprentice PDF & Print Versions ($108 value): A book for complete beginners to Apple’s brand new programming language – Swift 2.
  2. iOS Apprentice Fourth Edition PDF & Print Versions ($108 value): Learn how to make iPhone and iPad apps from the ground up, with a series of epic-length tutorials for beginners!
  3. iOS 9 by Tutorials PDF & Print Versions ($108 value): Learn about the new APIs in iOS 9 such as Core Spotlight, Multitasking, UIStackView, and App Thinning.
  4. watchOS 2 by Tutorials PDF & Print Versions ($108 value): Learn about WatchKit UI controls and layout, Glances, notifications, deep linking with Handoff, and more!
  5. Core Data by Tutorials Second Edition PDF & Print Versions ($108 value): Take control of your data in iOS apps using Core Data, Apple’s powerful object graph and persistence framework.
  6. iOS Animations by Tutorials Second Edition PDF & Print Versions ($108 value): Learn how to make iOS Animations in Swift 2 through a series of hands-on tutorials and challenges.
  7. 2D iOS & tvOS Games by Tutorials PDF & Print Versions ($108 value): Learn how to make your own iOS and tvOS games using Swift 2 and Apple’s game frameworks, Sprite Kit and GameplayKit.

Video Tutorials

  1. 1-year raywenderlich.com Subscription ($228 value): Get full access to our complete catalog of video tutorials – plus get access to a new video tutorial each week!

Bonus Loot

  1. raywenderlich.com T-shirt ($25 value): Sport a stylish gray t-shirt with a “Eat, Drink, Swift” design!
  2. Plus… cold hard cash for a new iPhone 6S and an Apple TV! ($350 value)

Once again, a huge thanks to everyone who donated prizes for the iOS 9 Feast! These are all amazing resources for developers that we hand-picked and highly recommend.

And the 1 grand prize winner who will get this huge prize pack of over $8,000 in value is… wait for it…

Epic Grin

Kyle Bashour (@kylebshr on Twitter)!

Huge congrats to Kyle! We will be in touch soon to arrange delivery of your prizes.

If you didn’t win the grand prize don’t worry – we have 150 more second prize winners to announce! :]

Second Prize Winners

Again, anyone who sent a tweet in the past month with the #ios9feast hash tag was eligible to win a second prize – and here are the lucky 150 random winners! :]

  1. @_AseR_
  2. @_mitchellporter
  3. @AgisilaosTsaras
  4. @akonakov
  5. @alessandroorru
  6. @alf147
  7. @alshootfa
  8. @anibalravila
  9. @APCorc
  10. @ashstampede
  11. @AsifHamza
  12. @BakkerFG
  13. @bballentine
  14. @BhagatBhavik
  15. @bhansmeyer
  16. @bilgehoor
  17. @billcod
  18. @Bobl_ee
  19. @borjareinares
  20. @brevansio
  21. @brian_henderson
  22. @Brock
  23. @cabhara
  24. @calkinsc3
  25. @CanvasModel
  26. @casanovam
  27. @Cassebart
  28. @CenCen123
  29. @chiplambert
  30. @ChristianLysne
  31. @chucklin
  32. @clintcabanero
  33. @comfly
  34. @crisredfi
  35. @Cro___Sensation
  36. @dadederk
  37. @dahenrom
  38. @danycoro
  39. @Darren_Branford
  40. @davidskeck
  41. @Deivuh
  42. @DiegoCaroli
  43. @DigitalGeekLife
  44. @Dinalli
  45. @ElautJelle
  46. @esnandakumar
  47. @f_messina
  48. @filippocamillo
  49. @FlockOfSwifts
  50. @foamx
  51. @fra3il
  52. @g_lecki
  53. @gallaxya
  54. @GausterLukas
  55. @gerdgrossmann
  56. @hamzashaikh1hamzashaikh1
  57. @hayden_evans
  58. @heyAndrew
  59. @HolgerLiesegang
  60. @hossamghareeb7
  61. @hp_om
  62. @hyun2012
  63. @IJNanayakkara
  64. @iMaddin
  65. @imvimm
  66. @IndieGameDevBot
  67. @itermar
  68. @iuridium
  69. @jandro_es
  70. @jarbyvid
  71. @JDawg927
  72. @JimGrosch
  73. @Joshua_Qn
  74. @jpkv2
  75. @JuanpeCMiOS
  76. @jurvistan
  77. @K0nserv
  78. @kallolfrisky
  79. @Katm__el3brat
  80. @kennetheyoung
  81. @kevin_vavelin
  82. @kravik
  83. @LagMacStudio
  84. @Lcs1969Lee
  85. @liuyi0922
  86. @LuoJie6
  87. @maguzmanesp
  88. @markstickley
  89. @mehmeet43
  90. @mepamidi
  91. @mglttkx
  92. @MichaelTackes
  93. @mjoseoli
  94. @natashasgodwin
  95. @nicktesla2010
  96. @nomad00
  97. @notlaugh
  98. @octermircty
  99. @Opereira
  100. @Orangecoding
  101. @panchapol
  102. @PathToCode
  103. @patrickchampion
  104. @peeterrussak
  105. @phaugsoen
  106. @popovici_ionut
  107. @Ptitaw
  108. @Pym
  109. @rahusendax
  110. @rbarbosa
  111. @Rim21Tech
  112. @RJHComputers
  113. @rmorlen
  114. @Roberto_Pastor
  115. @roger_molas
  116. @rustproofFish
  117. @sachiny009
  118. @scascacha
  119. @segabor
  120. @shuoyang
  121. @sidasa
  122. @sidepelican
  123. @sightuary
  124. @Sir_Lawton
  125. @smithmgcsmith
  126. @SoftcodeSystems
  127. @sqlservercowboy
  128. @steveholt55
  129. @SuparjitoTeo
  130. @superboonie
  131. @SWBerard
  132. @The_Poor_Tom
  133. @thegrizzlylabs
  134. @theMarkEaton
  135. @timrupe
  136. @tmurrane
  137. @tomnazarenko
  138. @TomSmallwood
  139. @tripolev
  140. @tsom
  141. @twofly3
  142. @Umaks_vs
  143. @vacawama
  144. @visumickey
  145. @Vizeris
  146. @XamarinU
  147. @xcdu
  148. @xenoki
  149. @yarmolchuk
  150. @zyrikin

How To Claim Your Prize

If you’re a lucky second prize winner, please email my co-worker Christine your top 5-10 choices from the list below (in order of most wanted->least wanted).

Christine will then do her best to match you with your preference (keep in mind each prize only has a limited number available). You have 48 hours to claim your prize, otherwise we’re going to give them away to others (more on that below).

First come, first serve, so be quick!

Unclaimed Prizes

As explained above, there is a chance that some of the prizes may go unclaimed (especially with so many winners!)

So, after 48 hours, if there are any unclaimed prizes, we will give them away to forum members who post a comment on this thread. The prizes will be given away in order from those with the most overall posts on the raywenderlich.com forums to those with the least posts, in order to reward regular forum members.

So if you want one last shot at winning, just post on this thread and who knows, you might get lucky and win an unclaimed prize! :]

And That’s a Wrap!

And that concludes the iOS 9 Feast, we hope you all enjoyed it and got fat and happy along the way!

Congrats to all of the prize winners, and a huge thank you to everyone who supported us by purchasing our new Swift books, subscribing to our video tutorials, signing up for RWDevCon, or recommending our site. You are what makes all of this possible!

Thank you all again, and we’re now back to our regularly scheduled programming at raywenderlich.com!

Aww Yeah!

The post iOS 9 Feast Giveaway Winners! appeared first on Ray Wenderlich.

UIStackView and AVFoundation – Podcast S05 E01

$
0
0
Join Mic, Jake, and Sam to learn about the merits of UIStackView, followed by a deep dive into AVFoundation

Join Mic, Jake, and Sam to learn about the merits of UIStackView, followed by a deep dive into AVFoundation

Join Mic, Jake, and Sam to learn about the merits of UIStackView, followed by a deep dive into AVFoundation!

[Subscribe in iTunes] [RSS Feed]

Our Sponsor

This episode was brought to you by the kind folks over at Harvest.

Harvest is a time tracking tool built for understanding where your time is going. And for developers, it takes the pain out of time tracking. You can create a free 30-day trial at getharvest.com.

After your trial, enter code RAY to save 50% off your first month.

Interested in sponsoring a podcast episode? We sell ads via Syndicate Ads, check it out!

Links

Contact Us

Where To Go From Here?

We hope you enjoyed this episode of our podcast. Be sure to subscribe in iTunes to get notified when the next episode comes out.

We’d love to hear what you think about the podcast, and any suggestions on what you’d like to hear in future episodes. Feel free to drop a comment here, or email us anytime at podcast@raywenderlich.com.

The post UIStackView and AVFoundation – Podcast S05 E01 appeared first on Ray Wenderlich.

Video Tutorial: Beginning Native tvOS Apps: Series Introduction

Video Tutorial: Beginning Native tvOS Apps Part 1: The Basics Part One

Introducing the Unity Feast!

$
0
0

Introducing the Unity Feast!

With the close of our annual iOS Feast, we here at raywenderlich.com feel like we’re just getting the party started. Not to let a good party die, I’d like to welcome you to our first ever Unity Feast!

The Unity Feast is designed to take you from a complete beginner to Unity, to making your first game – all within a week. And the best part – it’s completely free!

Here’s how you can be a part:

  • Do 1 Tutorial a Day: Every day this week, we will be releasing a free Unity tutorial on our site. Go through each one to learn the basics of Unity development.
  • Enter the Unity Game Jam: After reading the tutorials, you’ll know enough to make a simple game on your own. So enter our Unity game jam over the weekend to make your first Unity game.
  • Win Prizes: Our Unity Tutorial Team will judge the games submitted in the game jam; the maker of the top-voted game will win a $50 Steam gift card and a new Apple TV! :]

Unity Feast Calendar

Here’s a peek at the menu for the upcoming week:

  1. First Course: Introduction to Unity
  2. Second Course: Introduction to Unity 2D
  3. Third Course: Introduction to Unity Animation
  4. Fourth Course: Make a VR Game With Unity and Google Cardboard
  5. Fifth Course: Introduction to Unity Particle Systems
  6. Sixth Course: Introduction to Unity UI System
  7. Dessert: Unity Game Jam

Let’s take a closer look at what’s inside!

First Course: Introduction to Unity

To start off the Unity feast, you’ll be served a tasty introduction of the engine. This tutorial is geared towards the new Unity user. The tutorial introduces you to the interface of the engine, and then you will make a game much like asteroids.

This tutorial doesn’t require any coding skills at all. It’s a gentle introduction that will get you up to speed relatively quickly.

Second Course: Introduction to Unity 2D

In the second course, you’ll be introduced to Unity’s 2D features. This tutorial will cover the basics of creating 2D games as well as understanding the 2D physics engine and animation system.

This is all done by creating a lunar lander game that is both fun to play and easy on the eyes. :]

Third Course: Introduction to Unity Animation

Animation is a huge component of making a successful games. Thankfully, Unity provides an excellent animation system. It is both comprehensive and fun to use.

In this tutorial, you’ll learn the ins and outs of working with the animation system by building a game that tasks with you with throwing pies at clowns. Doing so, will teach you the process of making objects move through 3D space. It will also cover the creation of state machines to manage your animations.

Fourth Course: Make a VR Game With Unity and Google Cardboard

Coming up fourth is a nice tutorial on VR (virtual reality). Whether you like it or not, VR is the next driving trend in gaming and Unity is hoping to be the preferred engine for creating VR games. Google Cardboard is a fun easy way to get started with VR without having to spend hundred of dollars on a dedicated VR headset.

This tutorial will walk you through the steps of using Google Cardboard to create a simple 3D game on your iOS device.

Fifth Course: Introduction to Unity Particle Systems

This tutorial is going to be tasting a little grainy. That’s because you’ll be eating lots of particles! Particles are ways to add that extra juice to your game to make it look awesome.

In this tutorial, you’ll learn the basics of working with Unity particles by creating both fire and an explosion. Don’t worry, you won’t have to take out an insurance policy to go through this one. :]

Sixth Course: Introduction to Unity UI System

For a long time, Unity was really hard to make user interfaces. It was clunky that required you to write lots of code in designated methods. While third party solutions did ease the pain, it wasn’t a solution that was fully embraced by the community.

With Unity 4.6, we saw the introduction of a brand new UI system that addressed all the previous issues. In this tutorial, you’ll walk through the basics of updating a game with the new UI system.

Dessert: Unity Game Jam

After chowing down a large meal, there’s nothing like having a sweet sweet dessert. In this case, you’ll be having jam and not just any kind of jam, but rather, a great big helping of a “game jam”.

The Unity game jam is a great way to practice what you’ve just learned by reading the previous tutorials. It will be a great learning experience, a ton of fun – and hey, you may win some prizes!

The Unity game jam will start on Friday, November 20th and ends at midnight on November 22nd. Your job is to create a 2D game in Unity, using some artwork we’ll provide to you. You can, of course, add your own art but the games should in some way make use of the provided artwork.

Winners will be announced on Friday, November 27th. The top winner will take home a new Apple TV and a $50 Steam gift certificate. Runners-up will also be receiving prizes as well.

Stay tuned for more details this Friday. Get ready to have fun, be creative, and well, knock our socks off!

About the Cooks

Finally, I’d like to take the time to thank the Unity team. The Unity team is composed of a group of passionate Unity developers. We were only formed in this summer and as you can see, in the past few months, we’ve cooked up some wonderful tutorials.

While you can find out more about them on our about page, I thought I’d take the time to introduce them here.


  • Joachim Baur

    Joa Baur is a German software developer. He started to code some 20 years ago (anyone remember Macromedia Director 4?). Nowadays he primarily uses Unity3D and WebGL to produce commercial applications such as configurators and product presentations.

    Other favorite passtimes include reading/watching scifi and listening to EBM music or his daughter playing the trumpet.

    You can take a look at his projects over on his website or play his logic puzzle game COMBIN3 (made with Unity) on Android or Windows Phone.


  • Sean Duffy

    Sean is a software engineer by day, and hobbyist game and tools developer by night. He loves working with Unity, and is also a Unity Asset Store developer with a special focus on 2D tools to help other game developers. Some of Sean’s more popular Unity Assets include his 2D Shooter Bullet and Weapon System and 2D Homing Missiles assets.

    You can find Sean at his personal blog or on Twitter


  • Georgi Ivanov

    Georgi is an independent iOS developer and consultant with background in server-side development. Every so often shares thoughts and experience on his blog. Whenever he’s not building apps, he spends his time reading interesting books or concocting a new kitchen disaster.

    You can find Georgi on Twtter and LinkedIn.


  • Todd Kerpelman

    Todd Kerpelman used to be a halfway decent game designer, until he tricked Google into hiring him on as a Developer Advocate, and now he spends his time making YouTube videos. He figures it’s just a matter of time until they discover he doesn’t know what he’s talking about, so he’s stockpiling snacks in the meantime.


  • Brian Moakley

    Brian is not only an iOS developer and fiction writer, he also holds the honor being Razeware‘s first fulltime employee.

    Brian joins Razeware with experience from companies such as ESPN’s online fantasy team and Disney’s Internet Group. When not writing or coding, Brian enjoys story driven first person shooters, reading some great books, and he runs his own “Let’s Play” channel on YouTube.


  • Pedro Pereira & Orlando Pereira

    Pedro Pereira and Orlando Pereira are two Portuguese game developers and founders of the Wicked Cat Studios. They both graduated in Informatics Engineering at the University of Beira Interior, Portugal. Currently, they have several projects together, in the fields of mobile computing, namely using the Unity engine.


  • Barbara Reichart

    Barbara Reichart is currently doing her PhD at TUM, where she teaches software engineering and iOS development. In her free time she develops games (Treeo Games). Her first published game is Tw!nkle. You can also follow her on Google+.

    You can find Barbara on Twitter.


  • Eric Van de Kerckhove

    Eric is a belgian hobbyist game dev and has been so for more than 10 years.
    He started with DarkBasic, RPG Maker, Game Maker & XNA and now he makes games using Unity.
    Eric also takes interest in 3D modelling, vector art and playing video games.

The Unity team does have some open spots. If you’d like to join our awesome team, feel free to send me an email at: brian-at-razeware.com

Where To Go From Here?

There’s only one place to go … and that’s raywenderlich.com.

Keep checking back every day for a new tutorial (sometimes two), and when you see the post for the game jam, start your coding!

The Unity team is thrilled to provide you with all this new tasty content. We had a blast creating it and we hope you like reading it.

To the feast and beyond!

The post Introducing the Unity Feast! appeared first on Ray Wenderlich.

Introduction to Unity: Getting Started – Part 1/2

$
0
0
Note: This tutorial is part of the Unity Feast. To see more tutorials being featured in the Unity Feast as well as to learn how to take part in the Unity Feast game jam, click over here.

unity-5-logo-cropped

It’s hard to believe that in only a little more than ten years, Unity has gone from a scrappy graphics engine available only on the Mac, to the current graphics powerhouse available on almost thirty platforms.

Unity has often been compared to a Lego set – a singular tool that can solve a multitude of problems. While this is true, I like to think of Unity as an ocean instead.

Why? Well, you can stay near the beach and dip your toes in the water while building some awesome creations. But Unity lets you go as deep as you want and gives you the ability to customize the environment, write your shaders, and now with with Unity 5.1, even rewrite the networking stack to suit the needs of your game!

This is the first in a series of Unity tutorials designed to get you up to speed; in it, you’ll stick to the shoreline while you build a killer sand castle. As the introductory tutorial, this will give you an eagle-eyed view of the engine environment and tools, while subsequent tutorials will focus on the details of each subsystem.

Even the sand castles in Unity are epic (photo by Gavin Filius)

Even the sand castles in Unity are epic (photo by Gavin Filius)

In in this Unity tutorial, you’ll learn the following:

  • How to install Unity and what the differences are between the Personal and Professional versions.
  • What the different views are that make up the Unity interface.
  • How to navigate within the Scene view.
  • How to add and manipulate GameObjects and their Components

The first part of the tutorial is all about familiarizing yourself with the Unity User Interface.

In the second part you will apply this knowledge to create your first game, a small space shooter. You will do so with the help of a fairy god mother that provides all the scripts and some models, so you can focus on the Unity Interface some more.

Playing the Game

This tutorial is geared for those with little to no Unity experience. Ideally, you should have some programming experience, but if not, don’t sweat it – we’ll walk you through the whole thing! :]

Getting Started

The first step of this tutorial is to download Unity here. But wait – there are two different versions: the Personal version and the Professional version. Which should you choose?

Screen Shot 2015-07-17 at 4.25.08 PM

Unlike previous versions, both versions of Unity make the same engine features available to you. Personal is free (as in beer), whereas Professional can be purchased for $1,500 or can be subscribed to for $75 per month. The most noticeable difference is that games created with the Personal version start with a Unity splash screen, whereas the Professional version does away with the splash screen and provides additional services to your game such as analytics and team asset sharing.

Unity has some pretty strict rules about how you can use the Personal edition; before you start writing your next killer Unity app be sure to check out the Unity FAQ to see if you’re eligible to use it.

For the purpose of following the tutorials the Personal Edition is sufficient, so push the Free Download button. This will lead to a download page. Simply click on the huge Download installer button.

Bildschirmfoto 2015-09-25 um 14.50.16

Run the installer and follow the instructions on screen, which means push Continue and accept the license agreement. Wait for the installation to complete then launch Unity; you’ll be prompted to login before you can go any further:

unity

You’ll need to create a free Unity account in order to use the software if you don’t have one already. To create a Unity account, click the create one link and fill out the following form:

signup

You’ll have to log in every time you use Unity, but it does offer an offline mode in case you need it.

Once you’ve created an account, logged into Unity, and confirmed all of your license details, the projects dialog will automatically appear. It allows you to create a new project and will look something like the following:

new-project

Click the New project button; you’ll see the dialog switch to the following:

Screen Shot 2015-07-20 at 3.50.07 PM

Name your project Space Debris and pick a location on your hard drive to save it. You’ll notice that you have two options: 3D or 2D. These two options determine the initial configuration of the editor; you can change these settings later if you decide to change your game type. For now, select 3D.

The Asset packages button lets you import custom packages into your project. For instance, if you’re making a first person shooter, you may want to import Unity’s first-person controller package.

Screen Shot 2015-07-23 at 1.24.51 PM

This is simply a convenience feature at the time of project creation; you’re able to import packages at any point during your project’s lifecycle. For this tutorial, you do not need any of the standard assets. Click on Create project and Unity will open with your first project.

Breaking Down the Interface

When Unity first opens, you’ll see a window that looks like this:

Screen Shot 2015-07-20 at 4.17.52 PM

The interface can be a bit overwhelming at first. Take a deep breath and tell yourself it’s going to be all right! :] The interface is highly customizable and can provide you with as much or as little information as you need.

In the upper right hand corner, you’ll see three buttons. Select the middle button, and from the list of options, select the 2 by 3 option:

Screen Shot 2015-07-20 at 4.22.16 PM

Your editor should now look like the image below and have the following sections:

ui

Here’s the breakdown of the various pieces of the editor:

1. Scene View

The Scene View is where you construct your game; it’s where you add all models, cameras, and other pieces that make up your game. This is a 3D window where you can visually place all the assets you’re using like so:

scene view

As you test your game in Unity, the scene view will update itself with the current game’s state, and you can even add new elements on-the-fly to the scene. When you stop the game, the scene view will revert to its original state. Any changes you make to the Scene View while you’re playing the game will be lost when it stops.

2. Game View

The Game View represents the player’s perspective of game. This where you can play your game and see how all its various mechanics work with one another:

game-view

The Game View has a aspect ratio selector, which lets you change the perspective of the view to match that of a specific screen aspect ratio (e. g. 4:3, 16:9, 16:10 …) or a device screen such as that of an iPhone or iPad. This allows you to make sure it looks good on all aspect ratios you want to support and that no important content is cut off.

Screen Shot 2015-07-23 at 5.14.42 PM

3. Hierarchy

The Hierarchy contains a list of all the current GameObjects being used in your game. But what is a GameObject? That’s an easy one: a GameObject is an object in your game.

YOU DON'T SAY?

OK, there’s a bit more to them than that! :] In essence, GameObjects represent points in space you customize through adding Components. Components permit GameObjects to project geometry, from a simple cube up to more complex 3d models of towers or monsters, emit light, act as camera or even create complex behavior via scripts.

GameObjects can also contain other GameObjects, which makes them quite useful for organizing your Scene. You’ll see GameObjects in action in the second part of this tutorial. Here a tiny preview into the fun you will have :]

hiearchy

A Scene typically represents a single level of your game, although you could theoretically put the entire game inside one scene. Any GameObjects actively being used in your game in the current scene will appear in the Hierarchy:

Every new scene starts with a Main Camera and a Directional Light, which are both GameObjects.

When you delete a GameObject from the Hierarchy, you’re effectively removing it from the scene.

4. Project Browser

The Project Browser contains all assets used by your game; it’s like a mini-filesystem. You can organize your assets by folders, and when you wish to use them, you can simply drag those assets from the Project Browser to the Hierarchy. Alternatively, you can drag them from the Project Browser to the Scene View. If you drag files from your computer into the Project Browser then Unity will automatically import those as assets for you.

project-browser

Unity organizes the assets in the OS file system to mimic the Project Browser. You may be tempted to make changes directly in the file system instead of in the Project Browser, but this is a big mistake that will break your assets – and possibly break your game!

unity-rage

Unity maintains metadata for each asset, so moving assets between folders on the filesystem breaks the metadata. If you need to make any organizational changes to your assets, always perform them in the Project Browser.

5. Inspector

The Inspector view lets you configure any GameObject. When you select a GameObject in the Hierarchy, the Inspector will list all the appropriate fields on that GameObject; for instance, a light will have a color field along with an intensity field. You can also alter values on your GameObjects while the game is being played.

Screen Shot 2015-07-23 at 5.45.46 PM

6. Toolbar

You use the toolbar to manipulate the various GameObjects in the Scene View. You’ll be using the following tools a lot as you develop your game, so get familiar with them by trying out all of them on your empty project!

The Hand tool is a “handy” tool (don’t worry folks, the jokes get worse!) with a bunch of useful features built right in:

Screen Shot 2015-07-25 at 7.53.54 AM

Select the Hand tool, then drag over the Scene View to pan the entire scene:

hand-pan

Right-click and drag to rotate the camera around your current position; notice that the hand icon transforms into an eye:

hand-rotate

Next, hold down Ctrl and Alt, right-click and move the mouse up to zoom into the scene. Moving the mouse down zooms out. Or if you don’t feel particularly coordinated, just just use the scroll wheel:

hand-zoom

Finally, hold down the right mouse button and use your WASD keys to move around the scene à la first person shooter. Likewise, you can move up and down by pressing E or Q respectively. To move even faster, hold down the Shift key as well:

hand-fps

The hand tool’s shortcut key is Q. To jump quickly to the hand tool, press the middle mouse button. Once you release it, you’ll return back to the previous tool you were using.

The Translate tool lets you select and position a GameObject in the scene:

Screen Shot 2015-07-25 at 7.53.54 AM

You’ll notice when you first select a GameObject you’ll see three colored arrows growing from its center. These arrows indicate the three-dimensional axes of the object: the x-axis is the red arrow, the y-axis is the green arrow, and the z-axis is the blue arrow:

translate-axis

Unity is known as a left-handed coordinate system. For a deeper explanation about left- and right-handed coordinate systems, check out this interesting article about coordinate systems from what-when-how.

Note: The three colored arrows are known as a Gizmo in Unity-speak. A Gizmo is 3D geometry or texture that provides information regarding the GameObject.

In this case, the Gizmo indicates the direction of each axis. As you learn more about Unity, you’ll be able to add your own Gizmos to indicate things such as spawn points, the location of cameras or even the wind direction. The great thing about Gizmos is they’re only displayed in the Scene View, and you can turn them off when they’re no longer needed.

There are many ways to move your GameObject with the Translate tool. You can select one of the arrows, then move the mouse; the GameObject will only move on that one axis. For example, if you selected the y-axis and moved an object while facing in a normal orientation, the GameObject would only move up or down.

The three colored boxes in the center of the GameObject let you move the GameObject on two axes; the square’s color indicates the direction it will NOT move. For instance, a green square means you can move an object on the x and z axes, but not on the y-axis:

translate-corners

The shortcut key for the translate tool is W.

The rotate tool, unsurprisingly, lets you rotate objects:

Screen Shot 2015-07-25 at 7.53.54 AM

You’ll notice three spherical colored lines when you select an object to rotate; these lines indicate the axis to rotate around. Simply select the line and drag your mouse to rotate the GameObject. To free rotate without being constrained to an axis, select the space between the lines and move your mouse:

rotate

The shortcut key for the rotate tool is E.

The Scale tool lets you scale a GameObject either along a single axis, or proportionately on all axes.

scaleTool

To scale an object along an axis, select the GameObject then drag the square end of an axis line; the GameObject will scale along that axis. To scale the entire GameObject, select the center point of the GameObject and drag the mouse either forwards or backwards to scale the GameObject up or down respectively:

Scaling the Tower

The shortcut key for the scale tool is R.

Note: Some of you may be a bit confused by the shortcut keys. You’d assume the Scale shortcut would be the S key instead of R. Believe it or not, there is a method to the madness. Do you notice a familiar pattern in the shortcut keys…perhaps one right at your fingertips?

Yep, it’s the top row of the keyboard! :] Unity assumes you’re using the mouse with your right hand and keyboarding with your left. Your fingers, at rest on the home row, will be on the ASDF keys. You’ll note each shortcut key of the toolbar corresponds to a key above the home position. The keyboard shortcuts for the toolbar corresponds to the QWERT keys, from left to right.

Unity Controls

Unfortunately, occasionally you’ll try to press the W key but press the 2 key by mistake. This puts the editor into 2D mode and will look a lot like this:

In 2D mode, objects lose their depth

In 2D mode, objects lose their depth.

When that happens, simply press 2 again and the editor will revert back to 3D mode.

The Rect tool is primarily used with 2D GameObjects and User Interface (UI) GameObjects, although you can use it on 3D GameObjects as well.

rect-tool

The tool can resize, scale, and rotate 2D assets and also reset the pivot point, which is the center point of rotation for the object. The pivot point is represented by a large circle on the asset:

rect-tool

Can you guess its shortcut key? That’s right, it’s T.

The Gizmo display toggles tend to be a point of confusion; they’re more than buttons, in fact – they’re toggle switches that control how you position Gizmos in your scene.

The first switch toggles between Center and Pivot. When in Center mode, if you select two GameObjects, the Gizmo will be placed in the center of the two objects. Rotating the GameObjects rotates them around the center Gizmo. In Pivot mode, each GameObject rotates around its own pivot point, as illustrated below:

pivot-center

The second switch toggles between Global and Local space. In Global mode, you’re manipulating your object from the point of view of the world around it. The x-axis goes left to right, the y-axis goes up and down, and the z-axis goes forward and backwards like usual. Switching to Local mode works from the coordinate system of the object itself, and changes the axes to match that of the actual GameObject:

global-local

7. Play Buttons

The Play Buttons let you start and stop your game. The first button is the Play button:

Screen Shot 2015-07-28 at 10.43.26 AM

A few things happen when you press Play; First, your game will start, as expected. The button set will also turn blue to indicate the game is in motion:

Screen Shot 2015-07-28 at 10.48.21 AM

The entire design interface dims as well to indicate the game is active:

The top image is the editor while making the game whereas the lower image is the game being played.

The top image is the editor while making the game whereas the lower image is the game being played.

Remember, any changes you make on-the-fly will be lost once you stop the game. It’s a common mistake for Unity beginners and regulars alike to run the game and make a pile of changes – which all disappear when the game stops! :[ The interface dimming is supposed to help remind you of this unfortunate fact, but I find the color shade is too subtle to remind me all the time.

Thankfully, you can change this shading to suit. Open the Unity preferences (shortcut CMD-,) and you’ll see a list of colors in the Colors section that you can customize in your interface:

Screen Shot 2015-07-28 at 10.55.45 AM

The Playmode tint field controls the dimming color of the interface.

Screen Shot 2015-07-28 at 10.57.28 AM

You can choose any color; to reset to the original color simply click the Use Defaults button.

The next button is Pause:

Screen Shot 2015-07-28 at 10.43.26 AM

This pauses your game and lets you make modifications to the game. Just like in play mode those modifications will be lost once you stop the game. Regard editing game objects during play and pause as a cheat and balancing system that allows you to experiment on your game without the danger of permanently breaking it.

The final button is Step:

Screen Shot 2015-07-28 at 10.43.26 AM

This lets you step through your game one frame at a time; it’s handy when you want to observe animations on a frame-by-frame basis, or when you want to check the state of particular GameObjects during gameplay:

play

8. Miscellaneous Editor Settings

The final three controls handle miscellaneous aspects of the editor. The first is the Layers drop-down:

Screen Shot 2015-07-27 at 2.32.05 PM

You can use Layers for such things as preventing the rendering of GameObjects, or excluding GameObjects from physics events like collisions.

Next up is the Layouts drop-down; this lets you create and save the layout of views in your editor and switch between them. Unity is wonderfully customizable, and each of the different views in a layout can be resized, docked, moved, or even removed from the editor altogether:

dockable

Don’t worry though – you can always add views you’ve removed back to the interface. This lets you customize the editor for a specific task. For example, you may not want to have the Game View open when working with an animation, but you’d prefer to have the Animator and Animation Views open side-by-side.

Rearranging the windows every single time you wanted this specific layout would become tiresome very quickly. Unity saves you from this tedium by letting you save your layouts, which you can switch to at any time via the Window menu item:

The Window option from the menubar provides a list of views that you can use.

The Window option from the menubar provides a list of views that you can use.

Unity comes with a few pre-defined layouts, such as the 2 by 3 layout and Wide layouts:

Screen Shot 2015-07-27 at 2.32.21 PM

As you work on games in Unity, you’ll find yourself creating many different layouts to support your various development tasks.

The next button is the Service button. The service button is where you can add additional Unity services to the game. Clicking on the button will prompt you to create a Unity Project ID that will allow you to add services to it.

Screen Shot 2015-11-09 at 4.45.13 PM

Once you add a Project ID, you will be able to add services to your project. For instance, you can provide cloud builds to your project. This automatically builds your project for you so you don’t have to wait for each project build. You can also add Analytics, In-Game Ads, and Multiplayer support.

You can also add team members to the project, set age restrictions, and change some important project settings.

Screen Shot 2015-11-09 at 5.01.39 PM

The final button, Account, lets you manage your Unity account. It allows you to view your account data, sign in and out, and upgrade:

account

That covers the majority of the views you’ll use when making games, but there are many more views beyond just these. You can get an overview over them in the Unity documentation.

Where to Go From Here?

You made it through the introduction to Unity; in Part 2 of this tutorial you’ll put these concepts into practice as you create small space shooter. You’ll learn how to build games the “Unity” way and gain a deeper understanding of the various tools and techniques you’ll need to leverage to create your very own game.

Do you have any questions about this tutorial, or the Unity editor or any of its associated views? Leave a comment below and I’ll get back to you!

The post Introduction to Unity: Getting Started – Part 1/2 appeared first on Ray Wenderlich.

Introduction to Unity: Getting Started – Part 2/2

$
0
0
Note: This tutorial is part of the Unity Feast. To see more tutorials being featured in the Unity Feast as well as to learn how to take part in the Unity Feast game jam, click over here.

unity-5-logo-cropped

In Part 1 of this Unity tutorial series, you learned the ins-and-outs of the Unity interface. In this second part, you’ll work in the Unity interface as you create your first game, a small space shooter. Along the way, you’ll learn the following:

  • How to use the Project Browser to import and organize your assets.
  • The difference between GameObjects and Prefabs.
  • How physics work in Unity.
  • How cameras work and which types of projections are available.
  • The basics of Materials in Unity.

This tutorial is meant to be an overview of Unity’s various systems. You’ll be assembling a game from all the pre-created assets, while in subsequent tutorials, you’ll learn about Unity’s subsystems in depth while you create your own assets and write your own scripts.

There’s a lot to cover, so put your phone on airplane mode, lock the doors, and open your mind to the world of Unity!

Getting Started

Download the sample files for this tutorial; they contain three folders: game assets, models and the starter project. You can simply use the project that you worked on in the first part of the tutorial, or you can open the project from the folder starter project in Unity using File\Open Project and then selecting the folder.

Note: Opening projects in Unity is a little different than other programs. You can either click a Scene file in your file browser, or select the project folder from within Unity:

Screen Shot 2015-08-05 at 10.30.55 AM

Screen Shot 2015-08-05 at 10.34.22 AM

In your file system navigate to the the game assets folder from the collection of sample files, select all files in that folder, and drag them into the Project Browser in Unity:

Screen Shot 2015-08-04 at 12.49.11 PM

Note: If you don’t see the Project Browser, Select Window\Layouts\2 by 3.

Unity will import all files; this may take a little while. When Unity’s finished importing the files, your Project Browser will look like the following:

Screen Shot 2015-08-06 at 1.01.28 PM

Unity defaults to large thumbnails, but I prefer to work with lists instead. At the bottom of the Project Browser, move the slider to the left to shrink the assets thumbnails. Moving the slider to the right makes them larger:

Resize Assets

While it’s nice to have all your assets in one place, they’re not organized too well – or at all! It doesn’t seem like a big problem when you first start a project, but as your project expands, so will your collection of assets.

By organizing your assets up front, you’ll spend less time searching for your assets and more time actually building your game.

Your next step is to organize your assets into folders. In the Project Browser, press the Create button and select Folder from the list of options:

Screen Shot 2015-08-06 at 1.12.59 PM

Give the new folder the name Materials. Your Project Browser should now look something like the following:

Screen Shot 2015-08-06 at 1.15.11 PM

Now create the following five folders to hold the rest of your assets:

  • Models
  • Prefabs
  • Scripts
  • Sounds
  • Textures

Folders in Unity behave much like the ones on your computer. You can create subfolders and drag folders into and out of other folders. The underlying filesystem will match the organization in Unity, which makes it easy for you to find your assets outside of Unity.

Now, it’s time to get organized! Select the Bullet, Debris, GameManager, IonCannon, RendererFade, ScreenWrap and ShipController scripts and drag them into the Script folder.

Next, select the background-music, explosion and shoot sound files and drag them into the Sounds folder.

Finally, select the flint_like_rock_4787 texture and move it into the Textures folder.

Your Project Browser should now look like the following:

Screen Shot 2015-08-04 at 1.08.12 PM

At this point, you’re probably eager to start making your game. But before you get too far, you need to get into the habit of saving your work since Unity doesn’t offer an autosave feature. If Unity crashed or you lost your power, you’d lose everything except your project organization.

In order to save your game, you need to create a new scene. A scene can be one level of many in a game, or it could be the only “level” in the entire game. In this game, you’ll use just one scene for everything.

Press Command-S to save your game. A save dialog will open; name your scene Main like so:

Screen Shot 2015-07-28 at 5.23.49 PM

Note: You can download this third-party script to make up for the lack of an auto-save feature in Unity. Unless, of course, you’re one of those compulsive people who hit “Save” every thirty seconds. :]

Working with GameObjects and Prefabs

What’s a game without a player? Look inside models\player from the sample files; you’ll see an FBX file along with a few image files.

An FBX file contains all the data required to create a 3D model along with other things such as animations. The player file you’ll use in this Unity tutorial was created by ComboMash for his game Hextraction.

Select all the files in the player folder and drag them into your Project Browser. You’ll see the following dialog:

Screen Shot 2015-07-28 at 5.57.01 PM

Some image files convey extra information for Unity, but are saved as a standard image format. In this case, p_pod_normal.jpg defines the depths of a surface, which provides surface lighting information without the need to create additional geometry. This is called a normal map.

However, Unity thinks it’s dealing with a regular image. Click Fix Now to instruct Unity to treat this file as a regular normal map.

Once you’ve imported the player files, drag the hextraction_pod asset from the Project Browser into the Scene View as follows:

Screen Shot 2015-07-29 at 1.06.39 PM

Cool – you’ve created your first instance of a model. Unity correctly imported the textures and applied them to the model.

You’ll also notice the Hierarchy now lists the new GameObject:

Screen Shot 2015-07-29 at 1.12.20 PM

As noted in Part 1 of this tutorial series, everything in your Hierarchy will be a type of GameObject. A GameObject by itself contains what’s known as a transform, which has information about the position, scale, and rotation of the GameObject:

Screen Shot 2015-08-05 at 10.51.39 AM

You customize GameObjects by adding Components to them; you can think of Components as representing the behavior and appearance of the GameObject.

For instance, you can add a lighting Component to illuminate your GameObject. You can add an Audio Source to make your GameObject emit sound, or even write your own Components as scripts and attach them to GameObjects.

GameObjects can also act as containers. Click on the disclosure triangle to the left of hextraction_pod in the Hierarchy; you’ll see the following collection of GameObjects:

Screen Shot 2015-07-29 at 1.13.03 PM

A lot of these are empty GameObjects that represent the structure of a model. Unity creates these GameObjects when you import a model. Other GameObjects, such as the children of pod_mesh, contain Components such Skinned Mesh Renderers to display geometry on the screen.

You’ll notice that some GameObjects in the Hierarchy are labelled in black, while others are labelled in blue:

Screen Shot 2015-07-29 at 1.12.20 PM

The black color means it is a standard GameObject. The blue text tells you the GameObject is connected to other objects with a Prefab. Sometimes GameObjects also turn brown. This means they have lost the prefab connection.

Prefabs let you save GameObjects to be easily duplicated either using code or through dragging new instances into the Scene View. It is a bit like using sand forms. Except, the instances of the Prefab are all connected. When you change the prefab, the instances will change as well.

Once you have an instance of a Prefab in the Scene View, you can customize it as you like. There may be times when you want to push these changes to existing Prefabs (because you liked them) or reset the instance to the state of the original prefab (because you messed up).

Select hextraction_pod in the Hierarchy. You’ll see three buttons in the Inspector: Select, Revert, and Open:

Screen Shot 2015-07-29 at 2.10.50 PM

Select locates the Prefab in your Project Browser. This is particularly useful when you misplace your Prefab in a complicated folder structure within your Project Browser.

When you make changes to a Prefab, you’ll see an Apply button in place of Select. Apply lets you push your changes to all other instances of that Prefab. The Revert button reverses any changes made to an instance of Prefab to the state of the original Prefab. Finally, Open opens the model file in the program that generated it, such as Maya or Blender.

Currently, the player’s ship has a tiled grid underneath it, which looks a bit strange. Select the tile_reference GameObject from the Hierarchy; it’s a direct child of the hextraction_pod GameObject.

Note: Don’t forget you can type the name of the object you’re looking for into the Hierarchy’s search bar to save you time.

search

With tile_reference selected in the Hierarchy, delete the gile grid by pressing Cmd-Delete. Unity will present you with the following warning:

Screen Shot 2015-07-29 at 3.13.30 PM

Unity’s warning you that such a major change will break the connection to the Prefab. Since you’re sure you want to do this, click Continue. You’ll note that hextraction_pod is labelled in black text, indicating it’s reverted to a plain old GameObject:

Screen Shot 2015-07-29 at 3.17.20 PM

Next, right on hextraction_pod in Hierarchy, select Rename, and name it Spaceship.

Now drag Spaceship into the the Prefabs folder of the Project Browser:

Screen Shot 2015-07-29 at 4.05.42 PM

Dragging a GameObject into the Project Browser converts it into a Prefab without any extra effort on your part. You could create as many instances of the Spaceship by dragging them from the Project Browser and into the Scene View. Currently this only copies the model, but later it could contain script, audio setting, and much more. So you can already see, that Prefabs can be really helpful.

Create Prefabs

Finally, take a moment to keep the Project Browser organized: drag hextraction_pod into the Models folder and the p_pod_ files into the Textures folder.

Note: You could create a new folder just as you would for normal maps, but to make things easier you’ll put them in the Textures folder instead.

Controlling the Camera

A spaceship isn’t really useful if it can’t move. In this section, you’ll give the player control of the spaceship. To do that, you’ll need to deal with two things: the camera and the physics system. Don’t worry, you won’t need to deal with subatomic particle physics today! :]

First, you need to set up the ship. Select the Spaceship in the Hierarchy, then use the Inspector to set its position to (3.74, 1.99, 10) and the rotation to (270,0, 0) as shown below:

Screen Shot 2015-08-06 at 1.40.05 PM

Looking at the Game View, you can see that the ship is still a little too close to the camera:

Screen Shot 2015-08-06 at 1.40.55 PM

There are two ways to fix this: you can either move the ship further back, or you can configure the camera. Prepare to become a camera assistant! :]

Select the Main Camera in the Hierarchy; you’ll see a Camera Component in the Inspector. There are a ton of options here, but for now ignore everything except Projection and Field of View:

Screen Shot 2015-07-30 at 2.07.13 PM

You can choose Perspective or Orthographic for your projection field; this choice determines the ultimate appearance of the game. Perspective projection behaves very much like your eye does; the closer an object is to your eye, the larger it appears. Orthographic projections discard depth information; objects closer to you, or in this case, the camera, will appear the same size as objects farther away:

The two cubes in the left are being shown with Perspective projection while the cubes on the right are Orthographic.

The two cubes in the left are being shown with Perspective projection while the cubes on the right are Orthographic.

Generally speaking, 3D games should use a Perspective projection. Games without depth, like 2D games, should use Orthographic projection.

While your game has 3D elements, the gameplay is essentially 2D. In the Projection field, select Orthographic. Next, set the size to 18.85. Your Game View should look like the following:

Screen Shot 2015-07-30 at 3.09.50 PM

A spaceship should fly, shouldn’t it? To do this, you’d have to write some code in C# or UnityScript to move the ship frame-by-frame. To save you some work, the example files contain a script all ready to use. The question is, how do you add it to your ship?

A script is simply another type of Component, and there are lots of ways to add Components to GameObjects. You’ll experiment with a few methods in this tutorial.

For now, select Spaceship from the Hierarchy. Then select the Component option from the menu bar. At the bottom, you’ll see an option called Scripts with a flyout menu of available scripts. Select the Ship Controller script:

Screen Shot 2015-07-30 at 3.15.30 PM

Just as you can with other Components, you can define fields in your scripts that you can access in the editor. This gives you the ability to change properties of your scripts while your game is being played:

Screen Shot 2015-08-05 at 11.10.10 AM

Set Move Speed of your script to 22 and Rotation Speed to 2. The move speed determines the speed of the ship, while the rotation speed determines how quickly the ship can turn. Hit the Play button in the top middle of the Unity interface. This starts the game. Use the arrow keys to move your ship.

Unfortunately, your ship will fly off the screen, to Alpha Centurai and beyond. You’ll need to fix that.

Use the menu bar as before to add the ScreenWrap script to the spaceship:

Screen Shot 2015-08-05 at 11.11.56 AM

You’ll notice that this script has a field named Renderers, which takes an array of Skinned Mesh Renderers, that is, the geometry that creates a model. If a renderer isn’t onscreen, then it teleports the GameObject to another position on screen based on its movement direction and current position.

Expand the Spaceship node until you find the body GameObject, then drag body GameObject into the Renderers field:

Skinned Mesh Renderer

Now run your game. To infinity…and beyond! :]

Screen Wrapping

Introducing Physics

There’s just one major problem. In flying your ship around, you violated one of the laws of physics. No, not Newton’s laws of physics – the laws of Unity physics best-practices.

Unity uses physics for collision detection; if a GameObject does not have a RigidBody component it is considered a static colliders. This means Unity assumes that it will stand still, which allows for huge optimizations when it comes to collision detection. When you move those static objects around, Unity has to recalculate those optimizations, which adds unnecessary CPU time to your game.

To avoid this unnecessary CPU overhead, you’ll need to opt-into the physics engine by adding a Rigidbody Component. You’ve already added Components directly from the menu bar; this time, with the Spaceship still selected in the Hierarchy, click the Add Component button in the Inspector:

Screen Shot 2015-07-30 at 5.12.30 PM

You’ll see a Component menu appear; click Physics then Rigidbody:

Adding Component

This Component also has a lot of options. Is Kinematic is the one you’re interested in. Setting this option means that you want to move a GameObject manually but still want the object to register for collisions. This is useful when you’re moving items via scripts, like you’re doing here, or via animation.

Tick the Is Kinematic checkbox; since you aren’t using gravity in this game, uncheck the Use Gravity checkbox like so:

Screen Shot 2015-08-04 at 5.27.55 PM

The object of this game is to fly around and shoot various types of debris. Naturally, handling collisions will play a large role in this type of game. You’ll need to know when the player shoots an asteroid or when a player crashes into something.

Colliders let you listen to and respond to collisions. There are many types of colliders to use with basic shapes, such as Sphere Collider and Box Collider. There’s even a mesh collider that is based on a 3D model.

Colliders are indicated by a green outline.

Colliders are indicated by a green outline.

In this tutorial, you’ll keep things simple and use a Sphere Collider.

Select the Spaceship in the Hierarchy and click the Add Component button in the Inspector. Click Physics\Sphere Collider, and you’ll see a green circle behind the Spaceship:

Screen Shot 2015-08-04 at 5.42.00 PM

Uh, wait – why is the collider behind the Spaceship? That’s because the actual model of the Spaceship has been offset from the parent when you changed its position earlier.

With the Spaceship selected in the Hierarchy, find your Sphere Collider in the Inspector. Set Center to (0, 4.09, -0.72) and Radius to 3.14. Finally, check the Is Trigger checkbox. Kinematic GameObjects can’t register normal collisions, but they can listen to trigger events from other kinematic objects.

Your Component should look like the following:

Screen-Shot-2015-08-06-at-12.23.09-PM

The collider should now encircle the Spaceship, like so:

Screen Shot 2015-08-04 at 5.59.48 PM

Arming the Cannons

While flying around is fun and all, most players have an overarching desire to fire off a few dozen photon torpedos! :] A script’s been provided for you to help satisfy that craving.

Select the Spaceship in the Hierarchy, then drag the IonCannon script from the Project Browser to the Inspector:

Screen Shot 2015-07-31 at 12.58.45 PM

You’ll notice an Audio Source Component was automatically added to the GameObject. Some scripts require Components; if the Components aren’t found on the GameObject, they’ll be added automatically.

To make your objects play sounds, you need both an Audio Source and an Audio Clip. An Audio Source can be attached to any GameObject, while an Audio Clip is simply an audio file.

Drag the shoot sound from the Sounds folder in the Project Browser into the Fire Sound field:

Screen Shot 2015-08-05 at 11.51.37 AM

You’ll notice that the Ion Cannon script has a Bullet field. Your job is to create a bullet object. Don’t worry if you’re not an artist – a simple sphere will suffice.

Click the Create button in the Hierarchy. From the menu, select 3D Object, then Sphere:

Create Sphere

Select the Sphere in the Hierarchy, then use the Inspector to set scale to (.47,.47,.47). Select the Sphere in the Hierarchy and name it Bullet.

Since your bullet is going to be moving across the scene, it needs to opt-into the physics engine as well. Do you remember what you need to do? Give it a whirl and if you’re stuck, check the spoiler below.

Solution Inside SelectShow>

The bullet will need velocity to move, so make sure Is Kinematic is unchecked. Also, make sure Use Gravity is also unchecked.

The bullet will keep traveling even after it flies offscreen, just like your spaceship did originally. Drag the Bullet script from the Project Browser onto the Bullet GameObject. Now, when the bullet flies offscreen, it will automatically be destroyed.

Finally, drag your Bullet object into the Prefab folder of your Project Browser. This creates a Prefab of the bullet, which allows you to create lots of bullets using a script. Pew, pew :]
Now that you have your bullet created, delete the instance of the bullet from the Hierarchy.

Select your Spaceship again, and use the Inspector to add the Bullet Prefab to the Bullet field. The Inspector should look like so:

Bildschirmfoto 2015-09-25 um 20.26.37

Finally, the sky background is somewhat out of place. You’d expect a spaceship to fly in the black void of space, wouldn’t you? :]

Select Main Camera in the Hierarchy and use the Inspector to set Clear Flags to Solid Color and Background Color to black:

Bildschirmfoto 2015-09-25 um 20.27.53

Run your game and press space to blast away with the space key!

Shooting

Putting the Debris in Space Debris

So far you have a ship that can fire, but it would be far more interesting if there were something to shoot at. It’s time for you to add some asteroids to the mix.

Find the rock_d_05.obj file in your downloaded files and drag it into Unity’s Project Browser.

Double-click rock_d_05.obj and name it Asteroid.

This file only contains information about the model itself; it doesn’t have any animations included.

Drag the Asteroid model into the Scene View to create an instance of it. You’ll see that the asteroid is currently plain white:

Screen Shot 2015-07-31 at 4.03.14 PM

While you could make the argument that it’s a fragment of a snow-white comet, your job is to give the asteroid a texture…unless you want to make a career of creating snow-themed games. :]

Expand the Asteroid GameObject and selects its child object named rockLP001. In Inspector you’ll see it has a child GameObject that contains a Mesh Renderer Component. The renderer draws the object to the screen but needs a bit of help to do this – that’s where Materials come into play.

Materials determine the appearance of your objects. For example, a cotton shirt will look much different than a plaster wall would.

Unity achieves this by encapsulating a shader with each material. What’s a shader, you ask? It’s a simple program written in a C-like language that runs on the GPU. A shader can be simple enough to render a texture on a cube, or it can be complex enough to simulate water.

Unity provides many different shaders out of the box, for example to render a sky box, or make an object appear translucent.

Open the Materials folder in the Project Browser, and click the Create button. From the dropdown, select Material and give it the name Asteroid.

The Shader option lets you choose from one of the many pre-packaged shaders. The default Standard Shader has enormous flexibility, so leave it selected.

When an asteroid is hit, you’ll want to fade it out so set the Rendering Mode to Fade.

The Albedo property holds the actual texture; you can tint it by providing a color.

Drag the flint_like_rock_4787 image from the Textures folder in the Project Browser to the Albedo property:

Assigning Material

You’ll notice the Material looks a little too smooth, like it’s been polished:

Screen Shot 2015-07-31 at 9.20.53 PM

Under the Metallic property, you’ll see two sliders. The first slider determines the metallic appearance of the material, while the other determines how rough the texture is.

For now, set the Metallic slider to 0.219 and the Smoothness slider to 0.149. Your Material should now look like this:

Screen Shot 2015-08-03 at 6.59.41 PM

With the Material all configured, you now need to add it to the asteroid. Drag your Asteroid Material from the Project Browser to the Asteroid GameObject in the Scene View:

Adding Asteroid Texture

Awesome! You have an asteroid ready to cause lots of trouble, but first you need to add some behavior to it. Drag the Debris script from the Project Browser in the Scripts folder to the Asteroid.

The Debris script automatically added a Sphere Collider, Rigidbody, and Audio Source to the Asteroid. Set the center of the Sphere Collider to (0.01, -0.09, 0.89) and Radius to 1.49. Check the Is Trigger checkbox as well.

For the Rigidbody, uncheck the Use Gravity checkbox and check the Is Kinematic checkbox.

For the Debris script, set Min Speed to 15, Max Speed to 30 and drag the explosion sound file from the Sounds folder to the Explosion Sound field.

For the transform, of the Asteroid GameObject set the scale to (3.02, 3.02, 3.02).

Adding the Debris script also added the required Renderer Fade script. When a bullet collides with an asteroid, the asteroid should fade away instead of simply disappearing from the screen. The script only requires a fade time, so set Fade Time to 0.5.

As asteroids drift off the screen, they should wrap just like the Spaceship. From the Scripts folder in the Project Browser, drag the ScreenWrap script to the asteroid. Just as you did with the Spaceship, you’ll need to configure the ScreenWrap with the correct renderer.

The Asteroid has a child GameObject named rockLP001. Drag this child GameObject to the Renderers property in the Asteroid GameObject:

Screen Shot 2015-08-05 at 2.25.35 PM

Finally, drag the Asteroid from the Hierarchy to the Prefab folder in the Project Browser. Now that you’re done creating your Asteroid Prefab, delete the Asteroid instance from the Hierarchy.

The last thing you need is a spawn point for all the asteroids. Click the Create button in the Hierarchy and select Create Empty. Name your spawn point Debris.

You’ll want this spawn point to be on the same plane as the player; otherwise, the player will either fly over or under the debris. A good GameObject to use as a reference is missle_R_0 since it’s located in the center of the model.

Drag the Debris GameObject and make it a child of missle_R_0. The transform coordinates of Debris will then be relative to its parent GameObject. To match the coordinates of the parent, set the Debris position to (0, 0, 0). With this little trick you can be sure that Spaceship and Debris are on the same plane.

Next, move the Debris to the buttom of the Hierarchy view where it originally was:

Reset Position

Move the Debris GameObject 15 points to the right; its new position should be (20.0, 1.72, 7.06):

Set Spawn Point

Putting It All Together

Now that you have your ship and and an asteroid configured, you need to bring all the elements together and create a simple game.

Click the Create button in the Hierarchy and select Create Empty. In Inspector click on the name of the new GameObject and name it GameManager.

With the GameManager selected in the Hierarchy, click the Add Component button, select Scripts, then select GameManager. You’ll see that this action added an Audio Source as well. Also the GameManager component has several fields that you need to set that it will use to spawn asteroids.

Start with the Debris field. Make sure the Game Manager is selected in the Hierarchy, and drag the Asteroid Prefab into the Debris field. So what did you do here? The GameManager is responsible for spawning Asteroids. It uses the Debris field to decide which objects to spawn. You told it to use the Asteroid prefab.

Next still on GameManager set the Min Time to 2 and the Max Time to 5. This tells the script how quickly it should spawn asteroids. Set Total Items on Screen to 5, this limit the number of asteroids to 5 so that the player does not get overwhelmed. Drag the Debris GameObject to the Screen Debris field. This specifies that the GameManager should spawn asteroids on the Debris GameObject.

The GameManger component should look like the following:

Screen Shot 2015-08-06 at 12.23.09 PM

Finally, in the Audio Source Component, add background-music to the AudioClip field and make sure to check the loop checkbox.

Screen Shot 2015-08-06 at 12.26.15 PM

Run your game and check out how everything looks:

Playing the Game

Congratulations – you’ve built your very first game in Unity! In later tutorials, you’ll learn about the various subsections of Unity that really let you juice this game up. You’ll also learn how to write your own scripts to take advantage of Unity’s flexible API.

Where to Go From Here?

If you like, you can download the final project from this tutorial.

To learn more about Unity, check out our other tutorials over here. Unity also has a ton of great free content over on YouTube.

As always, keep checking this site for more tutorials in this series. If you have any questions, feel free to reach out to me in the forums below!

The post Introduction to Unity: Getting Started – Part 2/2 appeared first on Ray Wenderlich.


Introduction to Unity 2D

$
0
0
Note: This tutorial is part of the Unity Feast. To see more tutorials being featured in the Unity Feast as well as to learn how to take part in the Unity Feast game jam, click over here.

Lander-Introduction-250x250

Unity is an extremely popular and versatile game engine that has a long list of supported platforms and devices to its credit. Although 3D gaming seems to be the latest craze, a large portion of mobile, console and desktop games are presented in 2D, so it’s important to understand the features Unity provides for building 2D games.

In this tutorial, you’ll build a 2D space lander game and learn the following skills along the way:

  • How to work with sprites and the camera.
  • How to use Physics 2D components to handle collisions and gameplay.
  • How to set up 2D animation and states.
  • How to apply layer and sprite ordering.

If you don’t already have Unity 5, download it from Unity’s website.

Note: If you are new to Unity, you can read our Intro to Unity tutorial to get you up to speed.

Getting Started

Download the starter project for this tutorial, extract it, and open the LowGravityLander-Start project in Unity.

Open the Lander-Start scene located in the Scenes folder of your Project Browser. You should see the following in the Game view:

It's lonely out in space...

It’s lonely out in space…

The starter project is a functional 2D space lander game, but it has a few problems you’ll need to solve before you can truly call it finished.

Ready for lift off (and a perilous journey down to the closest landing pad)? Time to get started!

Note: 2D games in Unity, quite logically, use the 2D mode of the Unity Editor. You can choose 2D or 3D mode When you create a project from scratch:
2DMode
This option has already been set in the starter project for you.

Sprites in Unity

Sprites are easy to work with in Unity thanks to a great 2D workflow and built-in editor.

To add a sprite to your game, simply drag and drop it from your Project folder into your Scene view. To see for yourself how easy the process is, select the Scene view, then drag the playership sprite from the Sprites folder into your Scene view:

Lander-create-new-sprite

In the Hierarchy, click the playership GameObject Unity created for you and take a look at its details in the Inspector. Notice that Unity automatically attached a Sprite Renderer Component, which contains your playership sprite, to the GameObject:

Lander-sprite-renderer

That’s all it takes! The Sprite Renderer lets you display images as Sprites in both 2D and 3D scenes.

Delete the playership GameObject from the Hierarchy.

Sprite Modes

There are two different modes in which you can use Sprites:

Lander-sprite-mode-selection

  • Single: A single-image Sprite.
  • Multiple: A sprite with multiple elements, such as animations or spritesheets with different parts for a character.

A spriteheet is a single image that contains lots of smaller individual images like so:

thruster-spritesheet

The reason for using spritesheets is that every image you use in your game will take up one draw call. For a few dozen Sprites, this isn’t a big deal but as your game grows in complexity and scope, this could be a potential issue.

By using spritesheets, you are making just one draw call for lots of Sprites, thus giving your game a performance boost. Of course, organization of your spritesheets is just as important as using them, but that’s for another tutorial.

Sprite Editing

It’s convenient to pack multiple graphic elements into a single image for animations or objects that have lots of moving parts; Unity makes it easy to manage these spritesheets with a built-in 2D spritesheet editor.

You’ll use two spritesheets in this game: one for the lander’s thruster animation and one for an explosion animation. Both of these animations consist of multiple frames, which you can edit and slice using the Sprite Editor.

Lander-editor-ception-rageface

explosion-spritesheet.png has already been sliced and prepared into an animation for you, but the thruster-spritesheet.png still needs some attention. That’s your next task.

Click thruster-spritesheet.png in the Sprites folder of the Project Browser, then use the Inspector to change the Sprite Mode to Multiple. Finally, click Apply.

Next, click Sprite Editor:

SpriteEditorButton

A new window pops up to show the spritesheet automatically sliced into individual frames:

IndividualFrames

Click Slice, and notice that Automatic is the default slice operation:

Lander-default-sprite-slice-settings

Automatic means Unity will attempt to locate and slice your spritesheet on its own to the best of its ability. In this case, Automatic would work just fine, but you could also slice your spritesheet by cell size or by cell count.

Selecting the cell size option lets you specify the size of each frame in your spritesheet using pixel dimensions.

Click Grid by Cell Size under the Slice menu in the Sprite Editor:

GridByCellSize

Under Pixel Size, enter 9 for X and 32 for Y. Leave the other values at 0 and Pivot set to Center, then click Slice:

Slice and dice!

Slice and dice!

Click Apply in the Sprite Editor window to apply the changes to your spritesheet:
SpriteEditorApplyButton

You’re done – you can close the Close the Sprite Editor now. Your thruster spritesheet is ready for use.

Assigning Sprites to The Lander

Right now, you can’t actually see the lander in your game. That’s because it doesn’t have any Sprite Renderer components attached. There won’t be any spectacular landings – or crashes! – if the lander isn’t visble on the screen.

To fix that, click the Lander GameObject in the Hierarchy. In the Inspector, click Add Component, then type Sprite Renderer in the search text field. Finally, choose the Sprite Renderer component.

Now that you’ve added a Sprite Renderer Component, click the small circle icon next to the Sprite selector in the Component properties and select the playership sprite:

Lander-add-sprite-renderer-component-600px

Set the Order in Layer to 1.

Your next job is to assign the landing gear sprite.

Click the LanderFeet GameObject located under the Lander GameObject, then click the small circle icon next to the Sprite selector in the Sprite Renderer component properties. Then choose the lander-feet sprite in the Select Sprite window like so:

Lander-assign-lander-feet-sprite

Click Play; you’ll be able to see your Lander in the Game view. Use the WASD or arrow keys to fly around the screen:

Houston, we have liftoff!

Houston, we have liftoff!

The 2D Camera And Pixels Per Unit

Unity 2D projects have an orthographic camera view by default. Generally you’ll want to stick with this in your 2D games instead of using the perspective camera view. You can learn more about the differences between Perspective and Orthographic over here.

The image below shows the default camera configuration of your Lander project:

Lander-default-camera-orthographic-settings

As noted above, the Projection property is set to Orthographic.

Select the playership sprite in the Project Browser and look at its Import Settings in the Inspector. The Pixels Per Unit property is currently set to the default value of 100:

Lander-pixels-per-unit

So…what does “100” mean in this case?

A Word on Pixels Per Unit

Units in Unity don’t necessarily correspond to actual pixels on the screen. Instead, you’d commonly size your objects relative to each other on some arbitrary scale such as 1 unit = 1 meter. For sprites, Unity uses Pixels Per Unit to determine their unscaled size in units.

Consider a sprite imported from an image that’s 500 pixels wide. The table below shows how the width of GameObject on the x-axis would change as you render the sprite using different values for Pixels Per Units at different scales:

Screen Shot 2015-10-18 at 8.00.36 PM

How Pixels Per Unit conversions make me feel!

How Pixels Per Unit conversions make me feel!

Still not quite clear? The following scenario will help you think through what’s going on with the unit conversion:

Think about a game that uses a static camera and displays the the backdrop sprite fullscreen, similar to the wallpaper on your computer desktop.

backdrop.png is 2048 pixels tall, and has a default Pixel Per Unit ratio of 100. If you do the math, you’ll find the the backdrop GameObject in the Hierarchy will be 20.48 units tall.

However, the orthographic camera’s Size property measures only half the height of the screen, so to fit the exact height of the backdrop GameObject to the screen in full view, you’d use an orthographic size of 10.24:

ExplainPixelPerUnit

You don’t need to change the camera in your project, however, as the current size of 5 works fine for the moving camera in your game.

A Galaxy To Be Proud Of

The Max Size property of the sprite’s Import Settings lets you define a maximum size for your sprite, measured in pixels. You can override this setting for each platform you’re planning to target.

Zoom in to your scene view backdrop on the light blue galaxy. Note that it’s slightly blurry; when you import a sprite, the Max Size property defaults to 2048. Unity had to scale down your image to fit the default texture size, with a resulting loss of image quality.

To clear up your image issues, select the backdrop sprite in the Project Browser, and change Max Size to 4096. Click Apply, then wait for a few moments as Unity imports the backdrop of your Scene View once again. You’ll see the background suddenly become crisp and clear:

Lander-sprite-import-settings-max-size

Setting Max Size to 4096 lets Unity to use the full 4096 x 4096 texture instead so you can see the detail present in the original image.

However, this fidelity comes at a cost. Check the Inspector’s Preview area shown below; the size of the background texture is now 5.3 MB, up from the previous 1.3 MB:

Lander-texture-size-increase

Increasing the size of the texture increased its memory footprint by nearly a factor of 4.

Note: 4096 x 4096 is a fairly large image file; try to avoid using this size when possible, especially for mobile games. This project uses a large image only as an example.

Textures

You can also change the Format of a texture as shown below:

TextureFormat

You might want to adjust the Format of some textures to improve their color quality, but that also increases the memory footprint of the image. For example, modify the Format of the backdrop to 16 bits; the size of the texture grows to a massive 21.3 MB. Change the Format to Truecolor and you’ll increase that to 32.0 MB!

The Crunched setting takes a long time to compress, but it gives you the smallest possible file size of 1.2 MB and you can tune this even further.

The human eye would be hard pressed to see much difference between Compressed and 16 bits, so set the backdrop Format back to Compressed for the best ratio of texture size to quality.

When developing your own games, you’ll need to play with the Format settings to find the combination that results in the smallest texture size that still gives you the quality you’re looking for.

2D Colliders And Physics

Unity lets you adjust the gravity for the Physics 2D system just as you can in 3D games. Unity’s default gravity settings for a new project are the same as Earth’s gravity, by definition, 9.80665 m/s2. But you’re landing your spaceship on the moon, not Earth, and the gravity on the moon is roughly 16.6% of Earth’s, or 1.62519 m/s2.

Note: The gravity in your starter project was set to -1 to make it easy to fly around and test the game right away.

To modify the gravity of your game, click Edit\Project Settings\Physics 2D and use the Physics2DSettings Inspector panel to change the Y value of Gravity from -1 to -1.62519:

Lander-moon-gravity-Physics2D

Click Play to run the game; fly around a bit and see how the gravity changes the motion of your ship:

Lander-build-and-run-gravity-pulling-down

One small step up of gravity, one giant leap required for our thruster power!

One small step up of gravity, one giant leap required for thruster power!

Colliding With Objects

If you’ve already tried to navigate the Lander around the scene, you’ve likely collided with a rock or two. This is Unity’s 2D collision system at work.

Every object that should interact with gravity and other physics objects requires a Collider 2D component and a Rigidbody 2D component.

Select the Lander GameObject in the Hierarchy; you’ll see a Rigidbody 2D and Polygon Collider 2D Component are attached. Adding a Rigidbody 2D Component to a sprite puts it under control of Unity’s 2D physics system.

Lander-collider-and-rigidbody2D

A Quick Lesson on Physics Components

By itself, a Rigidbody 2D Component means gravity will affect a sprite and that you can control the image from script using forces. But if you want your sprite to interact and collide with other objects, you’ll also need a Collider 2D component. Adding an appropriate collider Component makes a sprite respond to collisions with other sprites.

Polygon 2D Colliders are more performance-heavy than other simple colliders such as the Box or Circle Collider 2D Components, but they make more precise physical interaction between objects possible. Always use the simplest collider shape you can get away with in your game to ensure you achieve the best possible performance.

Colliding Polygons

Explore the Collider on your spaceship by selecting the Lander GameObject in the Hierarchy and clicking Edit Collider on the Polygon 2D Collider:

EditColliderButton

Hover your mouse cursor over the collider edges in your scene view; handles appear to let you move the collider points around; you can also create or delete points to modify the shape of the collider:

Editing a Polygon Collider 2D

Leave the shape of the Lander collider as-is for now.

Note: The code in the Lander.cs script attached to the Lander GameObject uses OnCollisionEnter2D to handle collisions with other objects in the game scene. If the magnitude of the collision force is above a certain threshold, the lander will be destroyed.

Your landing pad also needs a collider; otherwise your spaceship would fall straight through when you tried to land!

In the Hierarchy, click the LanderObjective GameObject, and press F to focus on the landing pad. In the Inspector, click Add Component and choose the Box Collider 2D Component:

Lander-box-collider-2D

Unity adds a Box Collider 2D component to the LanderObjective GameObject and automatically sizes the collider to match the sprite size. Cool!

Lander-box-collider-on-landing-platform

There are a few other things to keep in mind regarding Rigidbody and 2D Collider Components:

  • Enable Is Kinematic on Rigidbodies when you want to move your physics bodies via a transform component instead of letting gravity affect them alone.
  • You can also modify mass, linear drag, angular drag and other physics properties on your Rigidbody components.
  • Colliders can be used in Trigger mode; they won’t physically collide with other physics objects, but instead they let your code react to an event using the OnTriggerEnter2D() available on all MonoBehaviour scripts.
  • To handle collision events in your script code, use OnCollisionEnter2D() which is available on all MonoBehaviour scripts.
  • You can assign optional Physics2D materials to your Colliders to control properties such as Bounciness or Friction.

Note: You may not notice it when there’s only a few objects in a game, but when you have hundreds of objects onscreen, all involved in physics interactions, using simpler collider shapes will greatly improve the performance of your game.

You may want to re-think your strategy of using Polygon Collider 2D components if you have lots of objects colliding!

You may want to re-think your strategy of using Polygon Collider 2D components if you have lots of objects colliding!

Lander Animation

Your lander would not be complete without visible thrusters boosting out to counter gravity. Right now the thrusters work, but there is no visual feedback to tell you they’re firing.

Unity Animation 101

To assign animation to GameObjects in your scene, you attach an Animator component to the GameObject(s) you wish to animate. This Component requires a reference to an Animation Controller that defines which animation clips to use and how to control these clips, along with other “fancier” effects such as blending and transitioning of animations.

An Animation Controller for Thrusters

In the Hierarchy, expand the Lander GameObject to reveal four other nested GameObjects. Select the ThrusterMain GameObject; you’ll see it already has an Animator component attached, but it doesn’t reference an Animation Controller:

Lander-animator-component-no-controller-reference

With the ThrusterMain GameObject still selected, click the Animation editor tab. If you don’t see this tab in the editor’s main window, click the Window menu, then Animation:

CreateAnimationWindow

Click the Create button to create an Animation Clip:

Lander-to-begin-animating

Enter the name ThrusterAnim and place it in the Assets\Animations folder.

You should now see two new animation assets in the Animations folder of the Project Browser. ThrusterAnim is the animation clip that will hold the animation for the thruster effect, and ThrusterMain is the animation controller that will control the animation:

Lander-animation-assets-created

You should see an animation timeline in the Animation window at this point; this is where you can place and order the individual thruster sprite frames.

Click Add Property and choose Sprite Renderer\Sprite as the type of property to animate:

AddAnimationProperty

Lander-sprite-property-to-animate

Your editor should now look like the following image:

Lander-SpriteAnimation-Timeline

In the Project Browser, click the Sprites folder and expand the thruster-spritesheet.png sprite. Highlight the four sliced thruster sprites and drag them onto the ThrusterMain : Sprite timeline in the Animation editor.

The sprite frames end up bunched together on the timeline; you can fix that yourself. Start with the rightmost sprite; click the sprite, drag it over to the right and space it five seconds (0:05) apart from its neighbor:

Lander-assign-sprite-frames-to-animation

Select the last frame and press Delete to remove it.

DeleteLastFrame

Click Record once in the Animation window to toggle off record mode for this clip; this prevents any accidental changes to the animation:

Lander-toggle-record-off

Time to configure the animation controller.

The Lander.cs script currently sets Animation Parameters to true or false, depending on whether or not the player is firing the thrusters. The animation controller will evaluate these parameters and allow certain states to be entered or exited.

In the Project Browser, click the Animations sub-folder, then double click ThrusterMain.controller. This opens the Animator editor, where you’ll see the controller Unity automatically added for you when you created the animation clip on the ThrusterMain GameObject:

Lander-Animator-start

Right now, the thruster animation is running continuously. Logically, the thruster animation should only run if the player is currently firing the thruster.

Right-click the grid area of the Animator editor, and click Create State\Empty:

CreateStateEmpty

Use the Inspector to name the new state NoThrust. This is the default state for the animation when there’s no player input:

Lander-NoThrust-state

From Entry, the animator should flow directly to NoThrust and stay there until a boolean parameter becomes true. For animation state changes to occur, you’ll need to add connections using transitions.

Right-click the Entry state and choose Make Transition. Click the NoThrust state to add a transition arrow from Entry to NoThrust. Right-click NoThrust and click Set As Layer Default State. NoThrust should now appear orange as below:

AnimatiionControllerMakeTransition

The orange color indicates that the state will be the first state that will be run.

Using the Animator editor, click + in the Parameters tab to create a new parameter type Bool. Name it ApplyingThrust:

Lander-create-ApplyingThrust-Parameter

Right-click NoThrust, click Make Transition, then click ThrusterAnim. This creates a transition that allows a state change between the two states. Now perform the same set of steps, but this time create a transition from ThrusterAnim to NoThrust:

Lander-thruster-animation-state-hookup

Click the NoThrust to ThrusterAnim transition line, then click + in the Inspector to add a Condition. This selects the only condition available – ApplyingThrust.

Ensure true is selected in the drop down. This indicates ApplyingThrust must be true for the animation to move to the ThrusterAnim state.

Lander-ApplyingThrust-Condition-true.png

Now edit the transition line from ThrusterAnim to NoThrust to use the same ApplyingThrust condition, but this time you’re checking for the false condition:

ApplyingThrustFalse

Lander-all-the-things

Your finished animation controller should look like the following:

Lander-finished-thruster-states

You can tweak the animation playback speed in the Animator editor to suit. Click the ThrusterAnim state, and in the Inspector, change the Speed property to 1.5:

Lander-ThrusterAnim-Speed

The thruster animation should react quite quickly to reflect the hair-trigger reactions from the player to appear responsive. Click both transition lines (the ones between NoThrust and ThrusterAnim) and use the Inspector to change the Transition related settings to 0. Uncheck Has Exit Time and Fixed Duration as well:

Lander-transition-settings-for-thruster

Finally, you need to apply the same animation and controller to the left and right thrusters. Select ThrusterLeft and ThrusterRight from the Hierarchy, then drag and drop ThrusterMain.controller from the Animations folder in the Project Browser to the Animator component’s Controller property:

DragThrusterControllers

Click Play to run the game; try out your new thrusters out with the WASD or arrow keys:

ThrustersPlay

Houston, we have lift off! :]

Sprite Sorting And Layers

No 2D engine would be complete without sprite-sorting abilities. Unity lets you sort and order sprites using a system of Layers and Order in layers.

Click Play in the Editor to run the game once again; use your worst piloting abilities to crash the lander into a nearby rock. Take a look at the Scene view in the Editor when the Restart button appears and notice how some of the rocks have disappeared behind the backdrop image:

Lander-incorrect-ordering

This happens because the rendering engine can’t decide the layering order of the sprites. All sprites, except for the ship, are currently set to use the Default sorting layer with a rendering order of 0.

To fix this, you can use a system of Layers and Order in layers to separate sprites. Unity will render sprites on these layers in the defined order of the layers. For each individual layer, Unity will use the Sprite’s Order in Layer numbering on each sprite to determine in which order it should render each sprite.

Click the Edit menu, then click Project Settings and choose Tags & Layers. Expand the Sorting Layers section.

Click + to add three new layers:

  • Background
  • Rocks
  • Player

Click and drag the handles next to each layer to ensure they’re ordered as listed above. The ordering of your layers here determines the rendering order in which Unity will render sprites on these layers:

Lander-layer-ordering

Click Backdrop in the Hierarchy; on the Sprite Renderer Component, click the Sorting Layer drop down and choose Background from the list:

Lander-backdrop-sorting-layer

Expand the Rocks GameObject and highlight all the child rock GameObjects. Use the Inspector to change the objects to use the Rocks Sorting Layer like so:

Lander-rock-sorting-layer

Since the rocks in your scene tend to overlap each other, they’re a good object to demonstrate how the Order in Layer property works for sprites on a specific Layer.

If you didn’t give each rock in the Rocks layer separate ordering values, you would notice rocks randomly ‘popping’ over others during gameplay. This is because Unity won’t consistently render the rocks in the same order, since they all have an order in layer value of 0.

Look for overlapping rocks and assign the ones in the front a higher Order in Layer value than the rocks behind them:

Overlapping rocks ordering in layer

Overlapping rocks ordering in layer

Change the Sprite Renderer Sorting Layer properties for the Lander and its child GameObjects, and all Fuel GameObjects under Pickups to Player. This will ensure they are rendered in front of everything.

There is one problem however. What about the sprites for the thruster animations (and the lander’s feet that normally hide behind the lander)? If we don’t set a specific Order in Layer number for these and for the Lander itself, we will see some odd rendering problems!

Lander-order-in-layer-conflict-problems

Change the Order in Layer property for the Lander itself to be 2. Select each Thruster child GameObject, as well as the LanderFeet GameObject, and set their Order in Layer values to 1.

When the lander touches down on the landing pad, the pad sinks down a little to show that you’ve landed. The landing pad and rock sprites overlap each other, so for the effect to look right, you’ll have to order the landing pad behind the rock.

Change the LanderObjective sprite to use the Rocks layer, and assign it an Order in Layer value of 0.
Set the rock underneath the LanderObjective to use a Order in Layer value of 1:

LanderObjectiveAndRockUnderneath

Finally, click the Explosion prefab in the Prefabs folder and change its Sorting Layer to Player:

ExplosionPrefabLayer

Click Play and test your piloting skills by picking up fuel supplies and touching down on the landing pad – just be careful not to apply too much thrust in any one direction so you avoid the rocks! :]

FinishedLanding

Where To Go From Here?

You can download the completed project from this tutorial here.

You’ve covered most of the important 2D design features of Unity, and you have a fun little gravity lander game to show for it!

If you’d like to dive deeper into Unity’s 2D tools and features, you should definitely start by reading through the official Unity 2D game creation page.

Hopefully you have enjoyed this tutorial – please join in the discussion using the Comments section below and post any feedback or questions you have. I look forward to chatting with you! :]

The post Introduction to Unity 2D appeared first on Ray Wenderlich.

Video Tutorial: Beginning Native tvOS Apps Part 4: User Input

Introduction to Unity Animation

$
0
0
Note: This tutorial is part of the Unity Feast. To see more tutorials being featured in the Unity Feast as well as to learn how to take part in the Unity Feast game jam, click over here.

CakeTheClown

Games with animations feel more polished and fun. Fortunately, Mecanim, Unity’s animation system, provides ample possibilities for animating GameObjects. In this tutorial, you will learn the basics of animation by throwing cake at a moving clown.

You’ll learn how to

  • Create animations
  • Use a state machine to switch between animations
  • Connect animations to scripts

By the end of the tutorial, you will be able to spice up your own game — with or without clowns :]

Note: This tutorial is meant for beginners. While it does not require any prerequisites, I recommend you familiarize yourself with the Unity user interface in our Unity: Getting Started tutorial.

Getting Started

Download the starter project and open it in Unity. It provides you with some initial graphic and audio assets, along with a Scene that already lets you throw cake around. Fun!

Music: “Circus Waltz” Kevin MacLeod (incompetech.com)
Licensed under Creative Commons: By Attribution 3.0
http://creativecommons.org/licenses/by/3.0/

In order to follow the tutorial more easily, select the Default layout from the drop-down menu in the top right corner. Unity should now look something like this:

DefaultLayout

Double-click on GameScene in the Project Browser, then hit the Play button at the top to run the starter project. You’ll see a colorful background. Click on it to throw a piece of cake! The cake is animated using physics, which is not part of this tutorial. You can learn more about Unity physics here.

TemplateProject

Your basic project is now up and running. Ready – Set – Cake!

A Moving Target – Your First Animation

Now to add a clown. Align your Scene View to the Camera’s view by selecting the Main Camera in the Hierarchy and choosing GameObject\Align View to Selected from the menu.

Drag and drop Models\Clown from the Project Browser into the Hierarchy.

Add Clown Asset

In the Inspector, make sure the Position is set to (0, 0, 0). Change the Rotation to (0, 180, 0):

Clown in center

Time to create your first animation. The clown should move to the left, then to the right and finally back to its starting position.

From the menu, select Window\Animation. This view lets you create and manipulate animations. Drag and drop it next to the Console View.

Animation View

In the Hierarchy, make sure the Clown is still selected. In the Animation View you will see text reading, “To begin animating Clown, create an Animator and an Animation Clip.” Press the Create button below. In the file dialog enter MoveHorizontally as the file name and press Save.

As a result, Unity creates two files: MoveHorizontally.anim and Clown.controller. Additionally, it adds an Animator Component to the Clown (1), which points to the Clown.controller (2):

Created Animation Clip and Animator

For now, you only need to focus on MoveHorizontally. This is the Animation Clip that allows you to animate several properties of your clown, such as:

  • Position, rotation, and scale
  • Material color and light intensity
  • Volume of a sound
  • Variables in your own scripts

You do this using the Animation View. It is fairly complex, so take a look at the most important areas:

  • Property List to add or remove the properties to animate.
  • Time Line to preview or modify a specific frame (sample) of the Animation Clip. The numbers correspond to seconds and samples, so 3:14 means 3 seonds and 14 samples.
  • Dope Sheet for an overview of the keyframe timing for multiple properties.

AnimationWindow

Editing an Animation Clip

There are several ways to change property values in an Animation Clip. First, change the property directly to make the clown move to the left.

In the Animation View, click Add Property. From the drop-down menu select Transform\Position and click on the plus sign. In the Property List unfold Clown: Position by clicking on the tiny arrow to its left. Now the position has an x, y, and z coordinate — just what you’d expect for a 3D game.

Click on the animation’s Time Line and select a time around 0:15 to modify the clown’s position at this time during the animation. In the Property List click on the number after Position.x and enter -6. This adds a keyframe that changes the property’s value at this particular time.

Edit Animation Clip

Note: As soon as you moved the playback head in the Animation timeline, the Animation’s record button was activated. Additionally, Unity’s main playback buttons turned red. This indicates that all changes you make now will apply to the Animation timeline, not to the whole Scene. Be sure to exit the record mode when you finish configuring the animation.

Record Buttons

Now to check out another way to edit Animation Clips, this time by making the clown move to the right. In the Time Line, select a time around 0:45. Go to the Inspector and set Position x to 6. You will see that Unity adds another keyframe to the timeline.

Play the animation by pressing the play button in the Animator View. Hm, it’s running a bit too fast for our poor cake-throwing skills. Fix this by setting Samples to 12. Run the animation again — the clown’s a much easier target now.

Animation Clip Sample Rate

You did it! You created your first animation :] Time to create another.

Animating Sound

When the clown gets hit, you’ll want to play a sound. Make sure to first stop the animation recording mode, then drag and drop Audio/splatter from the Project Browser onto the Clown GameObject in the Hierarchy.

Add Sound

Select the Clown in the Hierarchy. In the Inspector, you’ll see that this added an Audio Source Component to the Clown. Disable the Audio Source by clicking on the check box in its top left corner. You only want to enable the sound when the clown is actually hit. Also, the sound is a bit loud, so set its Volume to 0.25. The result:

Audio Source Component Settings

Time to play the sound from within the Animation Clip. In the Animation View, click on MoveHorizontally. From the drop-down select Create new Clip.

CreateNewClip3

In the file dialog, name it Hit and click Save.

Click record in the Animation View. In the Time Line, move the playback head to 0:10, then in the Inspector enable the Audio Source by activating the checkbox in its top left corner. Repeat at 1:00, but now disable it. Take note: when you hit play in the Animation View, you will not hear the sound.

Observing changes to properties other than position and scale can be difficult. Use the Keyframe Navigation highlighted in the image below to check that the Audio Source toggles between enabled and disabled.

Bildschirmfoto 2015-10-02 um 17.35.40

Your Turn

Ready for a challenge? Of course you are :]

Create another Animation Clip named MoveVertically. In it, make the clown move up to (0, 3, 0), then down to (0, -3, 0), then back to the center. Also adjust the sample rate.

Solution Inside SelectShow>

Manipulating Animation Curves

The dope sheet offers a compact view for when properties change, but it is difficult to see what value a property has between keyframes. In Curves mode, you can see and control the precise value for each property over time.

Click on Curves at the bottom of the Animation View. For MoveVertically, it should look something like this:

Animation Curve

You can see that Unity derived a nice, smooth-looking curve from the keyframes you specified. In Curves mode, you can change this to create great art like those two curves:

Art or Chaos, let the critics decide :]

Art or Chaos? That’s for the critics to decide :]

With Curves, you get really detailed control over property changes. Experiment with it, and if you want to understand in detail what is going on, have a peek at the documentation.

Switching Between Animations – State Machines 101

Up to this point, you have created Animation Clips. You can run each of them, but you cannot change which animation plays over the course of your game. This is where state machines come in.

Unity already created a state machine for the Clown when you created the first Animation Clip. You can take a look at it in the Animator View. To do so, select the Clown in the Hierarchy and from the menu select Window\Animator. You should now see the Animator tab right next to the Game tab.

Animator View

There are several states already: MoveHorizontally, MoveVertically, Hit, Entry, Exit and AnyState. Basically, each state corresponds to an Animation Clip that is playing as long as the state is active.

You’ll also see an arrow that points from Entry to MoveHorizontally. This means MoveHorizontally is the Default State, the state that the state machine is in when first activated. It is colored orange.

Note: In case you have a small screen and do not see all the states, don’t worry. Just hold alt and move the mouse with the left mouse button down to navigate in the Animator View.

The layout of the states doesn’t influence behavior, so feel free to arrange the states in a way that suits you — just drag them around.

Your First Transition

So far, so good. Now you want the clown to switch between MoveHorizontally and MoveVertically as soon as the respective animations end. Switching from one state to another is called a transition.

To create your first transition, right-click on MoveHorizontally. Select Make Transition from the drop-down menu, then click on MoveVertically. This creates a transition between the two states. Do the same for the opposite direction, from MoveVertically to MoveHorizontally.

FirstTransition

Play the game: the clown now moves from left to right, then up and down, infinitely.

Animation With Transitions

But there’s something weird happening: the clown is cutting corners when switching between the states. You never told it to do that. What’s going on?

To answer the question, select the Clown in the Inspector while the game is running and switch to the Animator View. You will see a progress bar in the currently active state. Look closely and see that there is a short period when both states, MoveHorizontally and MoveVertically, have a progress bar at the same time. This means that Unity runs both states at once, blending one with the other.

Two states active at same time

Blending states can be useful; when you have a character that transitions from walking to running, for example, this looks more natural. But there are also cases where you do not want to blend two states. Fortunately, Unity provides you with settings that allow you to control the transition.

In the Animator View, click on the transition arrow from MoveHorizontally to MoveVertically. In the Inspector, you can now see the settings that control the transition. Unfold Settings by clicking on the triangle next to it. Set the Exit Time to 1 and the Transition Duration to 0. Do the same for the transition from MoveVertically to MoveHorizontally.

TransitionSettingsShort

Run the game. Now the clown will move horizontally and vertically, but never both at the same time.

Animation Without Transitions

Take another look at the transition settings:

  • Has Exit Time determines whether the transition can be triggered at any time, or only after the specified exit time.
  • Exit Time is the earliest time after which the transition can start. It is represented in normalised time. An exit time of 0.75 means the transition starts only when the animation is 75% complete.
  • Transition Duration and Fixed Duration allow you to specify how long the transition takes. If Fixed Duration is enabled, specify the duration in seconds. Otherwise, specify the duration in normalised time.
  • Transition Offset controls the offset of the time to begin playing in the destination state which is transitioned to. For example, a value of 0.5 would mean the target state will begin playing at 50% of the way through its own timeline.
  • Interrupt Source controls whether the transition may be interrupted, for example when another transition is triggered.

Sometimes it can be difficult to imagine what those parameters mean. Thankfully, the Transition Graph, which is directly below the transition settings in the Inspector, shows you precisely how each animation is configured:

Transition Settings Diagramm

Just do it! – The Any State

You’ll want to run a Hit animation whenever the clown is hit by a cake, regardless of which state the clown is currently in. How can you achieve this?

From what you’ve learned so far, you’d probably just create two transitions to the Hit state: one from the MoveHorizontally state, and another from the MoveVertically state. While this will work, it doesn’t scale. Imagine you have a game with a more complex monster using ten states. You could create ten transitions, but it would become confusing, and we want to keep everything as simple as possible.

You might already have noticed the turquoise box that says Any State. It is basically a shorthand way for drawing transitions from all states to a single target state. Perfect!

Right-click on the AnyState, select Make Transition, and click on the Hit state. Now your Animator View should look like this:

CompleteAnimator

When the Hit animation is complete, the state should transition to the MoveHorizontally state.

Try to do this by yourself. If you get stuck, have a peek:

Solution Inside SelectShow>

Control State Switches Using Parameters and Conditions

Next you need to tell Unity when it should play the transition between Any State and Hit, as this should not happen automatically. You only want the Animator to switch to the Hit state when the clown is actually hit.

For this, you can use parameters and conditions. A parameter is a variable that you specify on the Animator. You can use it to define a condition for a specific transition to happen.

Here’s how it works in practice:

In the top left corner of the Animator View, select the Parameters tab. Click on the + button. From the drop-down menu, select Trigger. This creates a new trigger. Name it hit. That’s it! You are now the proud owner of your first parameter.

CreateParameterCropped

Next, select the transition arrow from Any State to Hit. In the Inspector, scroll to the Conditions section. Right now it reads “List is Empty.” Click on the + button. This adds the hit trigger as a condition.

AddConditionToAnimation

The transition will now be triggered once the parameter hit turns to true.

To try it out manually, drag and drop the Animator View right next to the Game View, so that you can see both at the same time. Run the game. In the Hierarchy, select the Clown. In the Animator View, click on the radio button after the hit parameter. You’ll hear the splatter sound, and then the clown resets. Great — your Animator Controller works as intended.

Hit Triggered Manually

Types of Parameters and Combining Conditions

Triggers are useful, but of course there are more parameter types you can use:

  • Float: Fractions (0.1, 0.999, 6.31, …)
  • Int: Whole numbers (1, 5, 13, 1005, …)
  • Bool: True or False
  • Trigger: Boolean parameter that is reset to false once consumed by a transition

Each type can be used depending on your requirements. For example, an Int could count how often the player hits the clown and play a special animation the 10th time.

Furthermore, you can assign default values to every parameter in the parameter list of the Animator View.

AssignDefaultValues

A Condition is used to decide when a transition should happen. You can define more than one condition on a transition. In this case, all conditions have to be met to trigger the transition.

You can also express that, for example, the clown should transition to the hit state if it is hit or if a time limit is up. To do this, create a second transition between the Any State and the Hit state. In the Inspector, you now see two transitions. For each transition, you can separately define the triggering condition.

MultipleTransitions

Bull’s Eye – Combine Animations and C# Scripts

By now you’ve seen how powerful and flexible Unity’s animation system can be, even without a single line of code. But, of course, messing around with code is great fun, so triggering animations from scripts is what you’ll learn next.

Trigger an Animation From Code

Before you can react to a collision, you need to be able to detect it. Unfold the Clown in the Hierarchy and select its child Skin. In the Inspector, click Add Component and choose Physics\Mesh Collider. In the new Mesh Collider Component, tick on Convex.

You can now see a thin green border around the skin of the clown. Granted, the shape does not perfectly fit the clown, but it’s close enough.

MeshCollider

Try it out. Run the game — the cake (because it also has a Collider) no longer flies through the clown.

To detect this collision in code, select Skin in the Inspector. Click Add Component, and select New Script. Name the script CollisionBehavior, set Language to C Sharp, and press Create And Add.

When another Collider touches the clown’s Mesh Collider, it triggers OnCollisionEnter. Open CollisionBehavior in MonoDevelop by double-clicking on the file in the Project Browser.

Add the following code inside CollisionBehavior above the line void Start():

// 1
public bool collided;
 
//2
void OnCollisionEnter(Collision collision) {
  if (!collided) {
    collided = true;
    // 3
    GameObject clown = gameObject.transform.parent.gameObject;
    Animator clownAnimator = clown.GetComponent<Animator> ();
    // 4
    clownAnimator.SetTrigger ("hit");
  }
}

Here’s what the code does:

  1. Creates a bool variable that remembers whether the clown already collided.
  2. Only triggers the animation if the clown has not collided yet. The next line sets collided to true to make sure you will only trigger the Hit animation once.
  3. Fetches the Clown GameObject, which is the parent of the current gameObject, then uses GetComponent to retrieve the Animator.
  4. Calls SetTrigger on the clownAnimator. This makes the animator go to the Hit state. For other parameter types, you can use SetFloat, SetInt, SetBool or ResetTrigger.

Run the game. Have a good throw. When you manage to hit the clown, it will make a splash sound!

State Machine Behaviors: React to State Changes in Your Scripts

State Machine Behaviors allow you to script behavior that is state dependent. For example, you can make the clown shrink as long as it is in the Hit state. Give it a try:

In Unity, go to the Animator View and select the Hit state. In the Inspector, click on Add Behavior. Select New Script, name it ClownHitBehavior and press Create And Add.

Double-click on ClownHitBehavior to open it. You might notice that Unity already added a few methods which are commented out. Don’t worry about them yet — you will learn what each of them does soon enough. Instead focus on scaling the clown!

Unlike Alice, our clown shrinks, when it comes in contact with cake. (from pixabay under CC0 Public Domain

Unlike Alice, our clown shrinks when it comes in contact with cake. (from pixabay under CC0 Public Domain

To do this, add the startTime variable inside the ClownHitBehavior.

float startTime;

This variable will store the time when the Hit state was entered. You can use this to control the speed of the animation depending on the actual time instead of the frame rate. This ensures that the clown shrinks at the same rate no matter how fast the game is running.

Next, look for the (commented out) OnStateEnter method. In this method, you set the value of startTime. Replace it with this:

override public void OnStateEnter(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
  startTime = Time.time;
}

OnStateEnter is called when the state machine enters the Hit state. With Time.time you retrieve the time in seconds since the start of the game. While not all that great for creating a clock, this is really sufficient for shrinking your clown :]

Next, look for the OnStateUpdate method and replace it with the following code:

override public void OnStateUpdate(Animator animator, AnimatorStateInfo stateInfo, int layerIndex) {
  GameObject clown = animator.gameObject;
  clown.transform.localScale *= Mathf.Lerp (1, 0, Time.time - startTime);
}

OnStateUpdate is called on every frame while the Hit state is active. In every frame, you adjust the scale of the clown.

For this you first need to find the Clown GameObject. As the script is running on the Animator Component, you cannot simply access it via gameObject like you did before. Instead, ask the animator variable of the method for its gameObject and then store this in the clown variable.

Next, change the Clown GameObject’s scale using Mathf.Lerp. This method linearly interpolates between two numerical values.

Take for instance two different points on the screen. One is y-positioned on the left at 0 and the other is y-positioned on the right at 20. Passing in a .50 to Math.Lerp will return a point in the middle.

Call Math.Lerp with three parameters: the two values it interpolates between, in this case 1 and 0, and the time in seconds since the Hit animation started. Lerp then calculates the resulting scale. For example, at 0 seconds it will return 1, at 1 second it will return 0 and at 0.75 seconds it will return 0.25.

Hit play and toss cake at the clown until you get a hit — the clown shrinks and never reappears. A short game indeed!

Hit Clown Disappears

Note: In case you wonder what the other methods in a State Machine Behavior are for:
  • OnStateEnter is called on the first frame of the state being played.
  • OnStateUpdate is called after Update of MonoBehaviors on every frame while the state the behavior it is attached to is playing.
  • OnStateExit is called on the last frame of a transition to another state.
  • OnStateMove is called instead of OnAnimatorMove on MonoBehaviors for every frame as long as the state is playing.
  • OnStateIK is called after Unity calculates Inverse Kinematics for a humanoid character — for example, to allow it to grab an item.

Animation Events: Trigger Code From Your Animation

Time to make the clown fit for duty again. A great way to do that is through Animation Events, which allow you to call functions from the game object’s script when an Animation Clip is running.

First, you need a script with a method that resets the clown’s size. Select the Clown in the Hierarchy. In the Inspector, scroll to the bottom and click Add Component. Select New Script and name the script ResetClown with C Sharp as Language. Press Create and Add.

Open the ResetClown script in MonoDevelop and add the following code:

void ResetClownOnHit () {
  gameObject.transform.localScale = Vector3.one;
  gameObject.GetComponentInChildren<CollisionBehavior> ().collided = false;
}

In this method, you set the localScale of the clown back to 1 to restore its original size. Then you use GetComponentInChildren() to reference the CollisionBehavior on the Skin and make sure that its collided variable is set to false. If you leave out this step, your clown will still move, but won’t react to collisions anymore.

Now you need to create an Animation Event that calls this method. Switch to the Animation View while the Clown is selected in the Hierarchy and pick the Hit animation clip. In the Time Line set the playback head to 1:30. If your Time Line is not visible beyond 1:00, use your scroll wheel to scale it down. Then click on the button Add Event.

Add Event

Double click on the marker for the Animation Event you just created.

Bildschirmfoto 2015-10-02 um 15.45.28

In the dialog window, select ResetClownOnHit().

Bildschirmfoto 2015-10-02 um 15.44.52

This creates an Animation Event that calls the method ResetClownOnHit() at 1:30.

Run the game. Now the clown shrinks, then resets and begins moving again, ready to be clobbered by cake once more!

FinishedAnimation

Where to Go From Here?

You can download the finished project here.

In this tutorial, you got a glimpse of the possibilities of Unity’s animation system. But much to learn you still have, young padawan. Some reading suggestions:

For now, enjoy the power you have gained over the animation system and make your games more beautiful and interactive. If you have any questions or comments, please join the discussion below!

The post Introduction to Unity Animation appeared first on Ray Wenderlich.

Make a VR Game With Unity and Google Cardboard

$
0
0
Note: This tutorial is part of the Unity Feast. To see more tutorials being featured in the Unity Feast as well as to learn how to take part in the Unity Feast game jam, click over here.

Welcome… to the THIRD DIMENSION!

Transform a boring ol' top-down game (top) to an exciting VR game (bottom)!

Transform a boring ol’ top-down game (top) to an exciting VR game (bottom)!

It’s probably safe to say that everybody has been waiting for virtual reality experiences since that classic of modern cinema, “Lawnmower Man”, showed us the potential of technology. It promised us a delightful future of, um, virtual reality where we could all have telepathic powers. Or something like that.

In this tutorial, you’ll help humanity prepare for its future of telepathic abilities and virtual reality by learning to take a simple Unity game and make it work as a VR experience using Google Cardboard. You’ll find out how to:

  • Integrate a Cardboard camera into your projects
  • Modify UI elements so that they work in VR mode
  • Make buttons selectable in VR mode
  • Switch programmatically between regular and VR mode at run time

Note: At the time of writing, mind control and becoming a super human through VR stuff is not a viable technology, in spite of what “Lawnmower Man” showed us. So, until Apple has a mind control API, just stick with mastering its precursors.

What is Google Cardboard?

In theory, creating a VR experience is straightforward. Instead of displaying your world as a single image on screen, you display two images.

They come from two cameras placed a few inches apart, and the user views the image from the left camera with the left eye and vice versa, creating the appearance of depth.

Additionally, with some judicious use of motion sensors, you can detect the direction the user is facing. Combine that with the 3D world you’ve created, and you’ve got yourself an immersive experience.

IfOnly

In practice, it takes some pretty sophisticated hardware to display two images on a high-definition screen, along with tracking the user’s head, and putting that all into a device small and light enough that it doesn’t hurt your neck.

Well, it turns out that such highly advanced technology is probably in your pocket or sitting within arm’s reach. It’s in almost every smartphone, and that’s the idea behind Cardboard; it can take the display and sensors in your phone and turn them into a respectable VR device, using just some cardboard and plastic lenses.

Getting Started

Note: You’re going to be working with the Unity GUI quite a bit. If you’ve never worked with it before, you might want to take a look at our Unity GUI tutorial.

To get started making your own VR game with Google Cardboard, you’re going to need the following:

  • Unity Personal Edition, version 5.x
  • A smartphone, either an iPhone 5 or later or an Android phone running Jelly Bean or later on which to test. By the way, this tutorial will assume you’re working on an iPhone.
  • Oh, yeah, and a Cardboard unit.
Note: If you are new Unity and you are unfamiliar with the interface, you can get up to speed by reading the Introduction to Unity tutorial found on this site.

Wait… How Do I Get a Cardboard Unit?

Don’t have a Cardboard unit? Your best bet is to order it from any of the vendors listed here. It should cost you around $20 or $30, plus shipping. If you’re feeling like a DIY superstar, you could even make your own.

When buying a Cardboard device, look for ones that mention “V2” or “Cardboard 2.0”, because they fit a larger variety of phones, including big phones like the iPhone 6+. They also support user input with a button that’s covered in conductive metal tape that taps the phone’s screen when you press down on it.

Can I Do this Tutorial Without a Cardboard Unit?

Well, kinda. You’ll be able to run your game on your phone, and it’ll look like this.

VRFinal

You can approximate a 3D experience if you stare past the screen just right while playing. If you move your phone around, you’ll be able to control it just as though your phone were strapped to your head, and you can simulate clicks by tapping the screen.

Although you could play the game and get a sense of what it would be like if you were viewing it through a VR headset, it doesn’t mean you should. It’s kind of like the difference between eating chocolate and watching a friend savor a salted caramel chocolate bar while you’re incapacitated in a full body cast.

Long story short: if you’re too impatient to wait for that Cardboard unit to arrive, you can still learn from this tutorial, but you’ll get a lot more out of it with the right equipment.

The Sample Game — Ninja Attack is Back!

Take a moment to try out your sample game. Download and unzip the Unity starter project.

Next, start up Unity. From the welcome screen, select Open and then the StarterNinja folder to open the NinjaAttack project.

In the Project Browser, double-click MainScene in Assets. Then give the game a try by pressing Play.

You’re the ninja on the left. As monsters make their way across the screen, click anywhere on the screen to launch a ninja star and take ’em out! Take out 20 monsters and you win, but if a monster reaches the red zone on the left, you lose.

Stop those blobs!

The blobs are at it again. Will they ever learn?

Does this game look familiar? For those of you who are long-time readers of raywenderlich.com, you might recognize this as the same ninja game from your SpriteKit and Cocos2D tutorials. But this time it’s rendered in glorious 3D!

OldShootGame

Not that you’ll really notice most of that glorious dimension though. The entire game is top-down. It almost feels like a waste rendering all these polygons. Now you’re seeing why this game is the perfect candidate for VR.

Getting Started with Cardboard

The first thing you need to do is download the Cardboard SDK for Unity.

Next, import it into your project. From Unity’s menu, select Assets\Import Package\Custom Package… and then select the CardboardSDKForUnity.unitypackage you just downloaded.

Make sure everything is selected, uncheck the Legacy folder, and then click the Import button.

ImportPackageShot

Hack it Like It’s Hot

To get your game working as a VR experience, you need to perform a few quick ‘n dirty hacks.

From the Cardboard\Prefabs folder in the Project Browser, drag the CardboardMain Prefab into your scene. In the inspector, give it almost the same Position as your ninja main character — -(5.53, 1.13, 0.122) — and a Y Rotation of 90.

CardboardPosition

You’ll notice it’s a little bit higher than the ninja’s center to represent the fact that you’re looking through his eyes.

Next, select the Main Camera in the hierarchy and uncheck it in the inspector to disable it. Do the same thing for the raccoon-ninja object.

Now, run your game in the Unity editor again. You should see something resembling a 3D scene! And if you hold down the option key while moving your mouse around, your camera will move as if you were turning your head.

FirstPassVR

Running Your Scene on an iOS Device

InTheFuture

It’s great to be able to run your game in the Unity editor, but last time I checked, there was no way to fit a computer monitor inside a VR headset without some serious pain, hence why you’re also working on an iPhone.

  • Select File\Build Settings — iOS should already be selected as your default platform.
  • Click Player Settings and switch to the inspector
  • Under Resolution and Presentation, change the Default Orientation to Landscape Left.
  • In Other Settings, change your Bundle Identifier to be something appropriate for your organization. (Like com.<your_company>.NinjaAttackVR)
  • Change your Target Device to iPhone Only

PlayerSettingsNinjaAttackVR

Attach your iPhone to your computer, select Build and Run and give your export folder a name; it can be anything you’d like.

Unity will export your project, and then it should automatically open up in Xcode. If it doesn’t, start up Xcode and manually open the generated project. Run it, and try it out on your phone!

The first time you run your game, it takes you through a setup process where you can scan a QR code on your Cardboard unit. This lets the Cardboard SDK make a few minor graphical adjustments based on how far apart your lenses are, their distance from the phone, and so on.

CardboardSetup

Note: If the setup process displays the error message Problem in parsing the URL after you scanned the QR code of your Cardboard unit, you’ll have to modify the info.plist of your Xcode project as described here, in the Apple developer forums.

Now go ahead and insert your phone into your Cardboard unit. Turn your head to adjust the camera’s view, and enjoy some fairly convincing 3D graphics.

Make it a Game Again!

Being able to view your game world is great and all, but you need to bring the gameplay back. Specifically, you want to be able to shoot ninja stars in the direction you’re facing. That’s the first piece of play you’ll work with.

For UI, Cardboard supports a single button. It might seem limiting, but if you combine it with the motion tracking you get from moving your head, it allows for interactions that are more complex.

In Ninja Attack, you detect if your user is in VR mode with the Cardboard.SDK.VRModeEnabled property. You’ll check if the button is pressed with the Cardboard.SDK.Triggered property. If both of those come out to be true, you launch a ninja star in the direction the user is looking.

Open up your NinjaStarLauncher.cs script. You can find it attached to the GameLogic GameObject in the inspector.

Create a new private variable:

private Vector3 _vrShooterOffset;

Initialize it in your Start() method:

_vrShooterOffset = new Vector3(0.0f, -0.4f, 1.0f);

Replace Update() with the following:

void Update() {
  // 1
  if (Cardboard.SDK.VRModeEnabled && Cardboard.SDK.Triggered &&
      !_gameController.isGameOver) {  
    GameObject vrLauncher = 
         Cardboard.SDK.GetComponentInChildren<CardboardHead>().gameObject;
    // 2
    LaunchNinjaStarFrom(vrLauncher, _vrShooterOffset);
  } else if (!Cardboard.SDK.VRModeEnabled && Input.GetButtonDown("Fire1") && 
             !_gameController.isGameOver) {
    // This is the same code as before
    Vector3 mouseLoc = Input.mousePosition;
    Vector3 worldMouseLoc = Camera.main.ScreenToWorldPoint(mouseLoc);
    worldMouseLoc.y = ninja.transform.position.y;
    ninja.transform.LookAt(worldMouseLoc);
    LaunchNinjaStarFrom(ninja, _shooterOffset);
  }	
}

That will get things working. Here’s a look at what Update() does:

  1. You first check if the game is in VR mode and if the user has pressed the button by examining the properties on the Cardboard.SDK singleton object.
  2. After that, you call LaunchNinjaStarFrom() to instantiate a ninja star. You pass in two parameters:
    1. The first is the head GameObject. The Cardboard library moves it around for you, so it should already be pointed in the right direction.
    2. The second is a slight offset, so the method instantiates a ninja star slightly in front of and below the head GameObject, which looks a little more natural — otherwise it would look like you’re shooting ninja stars out of your eyes. Cool, but weird.

Since your Ninja Star GameObject is already designed to fly out from where it’s created, it will fire in the correct direction.

Give it another try! At this point, you can turn your head around and shoot bad guys. The win or lose logic still applies.

Take that, blobbies!

Take that, blobbies!

Fixing the Game Over Menu

As you might have observed, when the game is over you’re still left with the old Game Over menu. It not only shows up improperly in 3D, but you have no way of clicking on it.

Shockingly, this button renders poorly in 3D.

Shockingly, this button renders poorly in 3D.

The game uses a Display Canvas — as seen in the Unity New Gui Tutorial — to display the Game Over screen, which always displays on top of the game window.

This canvas is great for most game GUIs because it automatically scales itself to fit on top of your screen no matter what your game’s camera is doing, and it nicely handles different screen sizes.

But in this case, you need a GUI canvas that exists in the world itself, partly so it renders properly in 3D, but also because you don’t want it to stay locked to the camera.

You want your users to be able to look up and down so they can look at different UI elements and trigger the active one by clicking the button.

Creating a New Canvas

Select the GameOverCanvas in the Hierarchy, right-click on it and select Duplicate.

Rename the duplicated canvas VRGameOverCanvas, to distinguish it from the original one, and rename its GameOverTxt child object to VRGameOverTxt.

RenamedHierarchy

In the Canvas component of VRGameOverCanvas, change the Render Mode to World Space

In the Rect Transform component, change the Position to (-2.24, 1.1, 0.07), and the Y Rotation to 90.

Finally, change the X and Y Scale to be 0.009. When it’s all done, the VRGameOverCanvas should look like this:

NewGameOverCanvas

And you should see the two canvases roughly overlap each other in the Game View (when the game’s not running):

TwoCanvases

Where did these values come from? Truthfully, I just fiddled around with them until I had something that looked good when viewing them through the Cardboard camera.

Sometimes programming is more an art than a science. :]

Supporting Both Canvases

Next up, you’re going to alter GameController.cs so that it’s aware of both canvases. Open up the GameController script that’s also attached to the GameLogic GameObject.

Add the following two public variables to your class:

public Canvas VRGameOverCanvas;
public Text VRGameOverTxt;

Add the following line to the beginning of resetGame():

VRGameOverCanvas.enabled = false;

Replace GameOver() with:

public void GameOver(bool didIWin) {
    isGameOver = true;
    _didIWin = didIWin;
    string finalTxt = (_didIWin) ? "You won!" : "Too bad";
    if (Cardboard.SDK.VRModeEnabled) {
        VRGameOverCanvas.enabled = true;
        VRGameOverTxt.text = finalTxt;
    } else {
        gameOverCanvas.enabled = true;
        gameOverTxt.text = finalTxt;
    }
}

This displays the proper canvas and text objects, depending on whether or not you’re in VR mode (Cardboard.SDK.VRModeEnabled).

After you’ve saved your script, you’ll need to assign the correct objects to the new public variables.

Find the GameController script in the inspector. Click on the target next to each of the new variables, and select VRGameOverCanvas object as your VR Game Over Canvas variable and the VRGameOverTxt object as your VR Game Over Txt variable.

VRCanvasInGameController

Note: Are you wondering why you’re going through the trouble of supporting two canvases instead of just changing the existing one? Because eventually, you’re going to support both top-down and VR mode. Stay tuned!

If you were to run your game now, you would see that it properly shows the end-game screen in VR mode. You can look up and down and see the different parts of your interface; all that’s missing is a way for you to click that Play Again button.

ProperlyRenderedButton

Adding Gaze Input

Luckily, Unity has built-in support for “Treating the center point of the camera as a mouse cursor” when using a world-space GUI canvas, but you need to provide an extra script to make it work in VR space.

First, expand Cardboard Main\Head in the Hierarchy. Find the Main Camera there and rename it to VR Main Camera

RenameCamera

Select your VRGameOverCanvas object. You should see an Event Camera entry in the Canvas Component. Click on the target and select the VR Main Camera you just renamed.

PickVRCamera

Click on the EventSystem object in the Hierarchy. Click Add Component in the inspector and add the GazeInputModule script. This is a script that makes sure Unity’s GUI system understands how Cardboard’s camera system works.

Check the VR Mode Only checkbox, because you only want things to work this way when you’re in VR mode — not when you’re in top-down version of your game. And you can uncheck Show Cursor.

Finally, click the gear of the Gaze Input Module Component you just added and select Move Up. Do this one more time, so that it appears above the Touch Input and Standalone Input modules. This is required to make sure the Gaze Input Module takes priority over the other types of input that your game can process.

When it’s all done, it should look like this:

FinalGazeInput

Give it a try now! This time, when you center your view on the Play Again button, it should turn green, and pressing down on the Cardboard button will let you “click” the it to start a new game!

GreenInGameButton

Minor Gameplay Tweaking

So perhaps you found this version a bit harder to play in VR mode. This is partly because you have a reduced field of vision and it’s easier for enemies to slip by when you’re looking in the wrong direction. Also, you can’t change the direction you’re aiming nearly as quickly as you could before. You’re physically constrained by the speed at which you can turn your neck.

DumbSpine

You don’t want to penalize your players for choosing to play in VR mode! So how can you correct this?

BionicSpine

Oh, well, I was going to suggest slowing down the enemies. But… uh… your call, I guess.

Select your EvilSlimeEnemy Prefab in the Prefabs folder and open up the attached EnemyMover.cs. Add this code to Start(), right after you set thisSpeed:

if (Cardboard.SDK.VRModeEnabled) { 
  thisSpeed *= 0.85f; 
}

This leads to your enemies bunching up a bit. If you want to keep them spaced out, go to EnemySpawner.cs — it’s attached to your GameLogic object — and add these lines in SetNextLaunch() right after you set launchInterval:

if (Cardboard.SDK.VRModeEnabled) { 
  launchInterval *= 1.1f;
}

This will make your game a tad easier in VR mode — just enough that your player shouldn’t feel penalized for choosing to play this way.

Fixing the On-Screen Score

The other UI element you need to address is the on-screen score object, and you’re going to try a slightly different approach for this one. While it still needs to appear in VR mode properly, you want it to stay fixed to your camera no matter where you look.

Imagine projecting your score onto a piece of glass that keeps moving around so that it’s always about 2 meters away from where the player is looking. That’s the effect you’re going to create.

You’ll accomplish this by using another world canvas so it renders properly in 3D, but you’ll make it a child of your Cardboard Head object.

Select Cardboard Main\Head in the Hierarchy. Right-click on it and select UI\Canvas. Rename the new canvas to VRScoreCanvas. Change its Render Mode to World Space.

Give it the following values:

  • Position: (0, 1, 2.5)
  • Width: 400, Height: 100
  • Rotation: (0,0,0)
  • Scale: (0.0115, 0.0115, 1)

When you’re all done, it should look like this:

VRScoreCanvas2

Right-click on your VRScoreCanvas and select UI\Text to add a text child-object. Rename it to VRScoreTxt. Change its anchor point to be top-left. Give it a Position of (150, -65, 0) and a Width of 60.

In the text component, set Font Size to 18 and change the Alignment to right-aligned. Finally, change the Text to 999.

When it’s all finished, it should look like this:

VRScoreText

It might seem like your text is strangely aligned in the center of the screen, but in VR mode, you see much less of your world than you normally would, so this ends up being pretty close to the edge of your vision. Feel free to adjust it so it looks right to you on your phone.

Next up, add the plumbing to display your score using this text object. The process is similar to how you displayed the Game Over canvas.

Open up GameController.cs and add a new public variable:

public Text VRScoreTxt;

Next, you’ll update VRScoreTxt every time you update scoreTxt. In the ResetGame() method, add this line right after you update scoreTxt:

VRScoreTxt.text = "--";

Then add this line to GotOne(), right after you update scoreTxt:

VRScoreTxt.text = "" + _currScore;

Save your script, go back into Unity and you’ll notice the GameController Component of GameLogic now has an entry for your VR Score Txt variable. Click the target next to it and select your VRScoreTxt text object.

SelectVRText

Play your game again, and now you’ll see that your score appears up in the upper-left corner of your vision, and that it follows your head movement.

ScoreInGame

Swapping In and Out of VR Mode

Since your game works in both top-down and VR mode, you should give the user the ability to switch between them.

The UI for this is pretty straightforward. You’ll add a simple button to your top-down game that users can press to switch into VR mode. As a bonus, the Cardboard SDK automatically displays a back button you can use to go back into top-down mode.

Give it a try!

First, you’re going to add the code to handle swapping in and out of cardboard mode. Select GameLogic in the Hierarchy. Click Add Component in the inspector, select New Script and name the script CardboardSwapper.

Open it, and replace the class code with this:

public class CardboardSwapper : MonoBehaviour {
 
  public GameObject[] cardboardObjects;
  public GameObject[] monoObjects;
 
  // Turn on or off VR mode
  void ActivateVRMode(bool goToVR) {
    foreach (GameObject cardboardThing in cardboardObjects) {
        cardboardThing.SetActive(goToVR);
    }
    foreach (GameObject monoThing in monoObjects) {
        monoThing.SetActive(!goToVR);
    }
    Cardboard.SDK.VRModeEnabled = goToVR;
 
    // Tell the game over screen to redisplay itself if necessary
    gameObject.GetComponent<GameController>().RefreshGameOver();
  }
 
  public void Switch() {
    ActivateVRMode(!Cardboard.SDK.VRModeEnabled);
  }
 
  void Update () {
    if (Cardboard.SDK.BackButtonPressed) {
      Switch();
    }
  }
 
  void Start() {
    ActivateVRMode(false);
  }
}

The most important method of this class is ActivateVRMode where you toggle the value of Cardboard.SDK.VRModeEnabled. It’s what activates Cardboard’s VR mode.

The rest of the logic disables or enables various GameObjects in your scene, depending on whether or not you’re in VR mode. Calling ActivateVRMode(false) in Start() starts your game off in top-down mode.

You’ll also notice that you call Switch() when you detect the back button has been pressed on the Cardboard display. You can simulate this Cardboard.SDK.BackButtonPressed in the Unity editor by pressing the esc key, a feature you’ll no doubt find awfully handy for testing.

You do need to add just a bit more logic to your GameController script so that it properly displays or hides the correct canvas if you’re switching modes at the end of the game.

Open up GameController.cs, and add this method:

public void RefreshGameOver() {
    gameOverCanvas.enabled = false;
    VRGameOverCanvas.enabled = false;
    if (isGameOver) {
        GameOver(_didIWin);
    }
}

Save everything and go back to Unity to populate the values of the two GameObject arrays.

Select GameLogic in the Hierarchy and scroll down to the Cardboard Swapper component in the inspector.

For the Cardboard Objects array, give it a size of 1, and then fill in the Head child of the CardboardMain GameObject in your scene. Not only does this disable your Cardboard Head so you can go back to the top-down camera, but it disables VRScoreCanvas as well.

For the Mono Objects array, give it a size of 3, and then select Canvas, Main Camera, and raccoon-ninja from your scene (not from the Assets).

CardboardSwapperObjects

Finally, you need to add a button on the top-down canvas for the user. To save time, I’ve already made one for you — it’s in the prefabs folder.

Drag CardboardButton from Assets\Prefabs into the Hierarchy so that it’s a child of your Canvas object. Make sure that its Position is set to (-50, 50, 0):

CardboardButton

At the bottom of your button object, hook it up such that clicking the button will call the CardboardSwapper.Switch() method attached to GameLogic. You can follow this animation to see how it’s done:

HookupSwapperLogic

Give your game another try. Click on the button at the bottom-right of the screen to switch to VR mode, then click the back button in the Cardboard display (or press Escape in the Unity editor) to go back to top-down mode.

CardboardSwapping

Congratulations! You’re swapping VR Modes like a boss!

LikeABoss

Where to Go From Here?

Download the final Unity project here.

You now have the power to take any 3D game in Unity and make it a VR experience with just a little cardboard and some plastic lenses. It’s VR for everybody!

The build process for Android is almost the same as for iOS.

Google’s Unity Developer Guide provides some additional technical info.

And finally, you could even add Augmented Reality (AR) to your VR projects!

Lastly, take a look at any 3D game you might make in Unity and see if there’s anything that would translate well to a VR experience. Or, maybe this tutorial will inspire you to create something entirely new.

As always, please feel free to leave questions and comments below or in the forums!

Oh, and if you figure out how to control lawn mowers with your mind, let me know — I’m still working on that.

The post Make a VR Game With Unity and Google Cardboard appeared first on Ray Wenderlich.

Protocols in Swift, and Unity – Podcast S05 E02

$
0
0
Curious about protocols in Swift, or Unity? Then this one's for you!

Curious about protocols in Swift, or Unity? Then this one’s for you!

Join Mic, Jake, and Greg as they chat about protocols in Swift 2.0, and then move onto discussing Unity!

[Subscribe in iTunes] [RSS Feed]

Our Sponsor

This episode was brought to you by the kind folks over at Moltin.

Moltin is an eCommerce API that allows you to easily add eCommerce functionality to any mobile app in minutes. With just a few lines of code you can implement inventory, carts, the checkout process, orders and more.

You can get 3 months of free access to the platform, worth an amazing $147, at moltin.com/r/raywenderlich.

Interested in sponsoring a podcast episode? We sell ads via Syndicate Ads, check it out!

Links

Contact Us

Where To Go From Here?

We hope you enjoyed this episode of our podcast. Be sure to subscribe in iTunes to get notified when the next episode comes out.

We’d love to hear what you think about the podcast, and any suggestions on what you’d like to hear in future episodes. Feel free to drop a comment here, or email us anytime at podcast@raywenderlich.com.

The post Protocols in Swift, and Unity – Podcast S05 E02 appeared first on Ray Wenderlich.

Introduction To Unity: Particle Systems

$
0
0
Note: This tutorial is part of the Unity Feast. To see more tutorials being featured in the Unity Feast as well as to learn how to take part in the Unity Feast game jam, click over here.
Make particle effects like these!

Make particle effects like these!

Particles effects are like salt; just a small amount can add extra “pizzazz” to whatever you’re cooking up. Modern games that don’t use particle effects in some manner feel can quite bland.

Particles also add authenticity to scenes. They can be the foundation of a roaring campfire, or the luminous effects of a wizard’s spells. They can also be used to create smoke, dust, explosions, and even rainbow puke! :]

In essence, particles are small, simple images or meshes that are emitted and then manipulated by a particle system during their lifetime.

Back in the old days, you needed to know the black arts of graphics programming to make even a wisp of smoke. Thankfully, Unity makes creating particle systems quite simple. Unity uses a powerful, modular built-in particle system named Shuriken, which is quite easy to learn but also lets you create complex effects – once you get to know it.

In this tutorial you’ll learn the following:

  • How to add a new particle system in Unity.
  • What the most commonly used particle system modules do and how to use them.

Time to get started!

Note: This tutorial assumes you understand the basics of working with Unity. If you are new to Unity, or need a refresher, please see our Introduction to Unity tutorial.

Getting Started

Download the particle system starter project and extract it to a convenient location. You’ll use this as your starting point.

This tutorial has two main parts; in the first, you’ll build the flames of a torch, while in the second part you’ll create a bomb explosion effect.

Open up the Starter Project in Unity. The assets inside are sorted into several folders:

  • Materials: Holds the fire material.
  • Models: Contains the torch and bomb models and their materials.
  • Prefabs: Hold the bomb prefab.
  • Scenes: Contains the Torch and Bomb scenes.
  • Scripts: Holds the initial scripts.
  • Textures: Contains the texture for the fire material.

Adding a Particle System

A particle system generally emits particles in random positions within a predefined space, which can be shaped like a sphere or a cone. The system determines the lifetime of the particle itself, and when that lifetime expires, destroys the particle.

Once nice thing about particle systems is that they are components that you can add to any GameObject in the scene. Want to have your sharks emit lasers from their eyes? Simply add a particle system to the eye GameObject, and your sharks will be unstoppable! :]

Open up the Torch scene in from your Project Window and run the scene:

There’s not much going on at the moment. The torch hangs on the wall, but there’s no fire to be seen. You’ll need to add a particle system first.

Select TorchFireParticles inside the Hierarchy. Inside the Inspector, click the Add Component button. Search for Particle System and click to add it:

Screen Shot 2015-10-29 at 2.55.44 PM

Note: You might have noticed you didn’t add the particle system directly to the Torch GameObject. This is because the particles would be emitted from the middle of the torch, instead of from the fuel container at the top.

Play your scene; you’ll see you have particles emitting already:

True, it doesn’t look much like fire, but you’ll fix that shortly. But first, you’ll need to understand the current state of the particle system and how to change it.

Note: When you select a GameObject with an attached particle system, you’ll notice a black dialog in the lower right hand corner of the scene view. This dialog gives you the ability to simulate or stop the particle system. Clicking Simulate activates your particle system and changes the button to a “Pause” button. To stop the simulation, click the “Stop” button.

Screen Shot 2015-10-29 at 3.05.52 PM

This dialog is useful for designing particle systems that run on a fixed timeline, such as explosions.

A Closer Look at a Particle System

Take a look at the Inspector; you’ll notice the particle system Component you added has several sub-sections:

Each of these sub-sections is called a Module. These Modules contain the settings for the particle system. The Module expanded by default is known as the Main module:

The Main module is the meat and bones of any particle system in Unity, and the most common particle settings live here:

  • Duration: The length of time in seconds for the particle to run. Leave this at the default value of 5.00.
  • Looping: Repeatedly emit particles until the particle system stops. The cycle restarts once the Duration time is reached.
    Left: on Right: off

    On & off

    The fire needs to burn continuously, so leave this enabled.

  • Prewarm: Only used when Looping is enabled. The Particle System will act as if it’s already completed a full cycle on start-up.
    On & off

    On & off

    For your fire effect, leave this disabled to make it look like the torch was just ignited.

  • Start Delay: The delay in seconds before the particle system start emitting. Leave this at the default value of 0.
  • Start Lifetime: The initial lifetime in seconds for the particles. The particle is destroyed after this elapsed time.
    Top: 8 seconds Bottom: 3 seconds

    Top: 8 seconds
    Bottom: 3 seconds

    Set the lifetime to 1.2 seconds; this ensures the flame won’t be too tall.

  • Start Speed: The initial speed of the particles. The greater the speed of the particles, the more spread out they will be.
    Top: 2 Bottom: 10

    Top: 2
    Bottom: 10

    Set the speed to 0.75; this will make the fire effect slower and more dense.

Note: When you modify the settings of the particle system, you’ll see a preview of it in the Game Window. Keep an eye on this preview while following along. You’re also free to experiment with the values on your own to learn more about how each setting affects your system.

Before continuing, run your scene to see the effect of your changes:

The effect looks pretty cool already, but it looks a lot like steam, smoke or plasma — and less like actual fire. Admire what you’ve done for a moment, and then get ready for the next batch of Main module settings! :]

More Main Module Properties

You’ve set up the torch, but the fire effect still leaves a lot to be desired. Thankfully, the Main module has additional options to further refine the shape and behavior of your torch.

Select the TorchFireParticles GameObject in the Hierarchy and scroll down to the particle system, if it isn’t already open. Under the Main Module, take a look at the following properties:

  • Start Size: the initial size of the particles.
    Top: 0.2 Bottom: 1

    Top: 0.2
    Bottom: 1

    Set the size to 0.25; this is a manageable size that lets you see the individual particles more clearly.

  • Start Rotation: The initial rotation angle of the particles.
    Top: 0° Bottom: 45°

    Top: 0°
    Bottom: 45°

    Keep the rotation at ; the particles are round so you will hardly notice the difference.

  • Start Color: The initial color of the particles. Keep the color at the default value of pure white (255,255,255); you’ll color the fire via a texture.
  • Gravity Modifier: Scales the gravity value set in Unity’s Physics Manager window. If it’s set to 0, the gravity will be turned off.


    The image above is from a system with the gravity modifier set to 1, which makes the particles flow down like a waterfall. Leave the gravity in your system at 0; the particles will move upwards with the velocity you set in Start Speed.

  • Inherit Velocity: Starts particles with the same velocity as the particle system. This only works if the particle system has a Rigidbody attached.
    Left: 1 Right: 0

    Left: 1
    Right: 0

    Keep Inherit Velocity at 0; you don’t need this for the fire effect.

  • Simulation Space: Moves particles in Local Space along with the particle system; while in World Space, particles move freely once emitted.
    Top: local space Bottom: world space

    Top: local space
    Bottom: world space

    Leave your simulation set to Local Space. The effect will only be visible once the particle system is moved.

  • Play On Awake: Starts emitting immediately when enabled. If this is turned off, you have to manually start the particle system via script or an animation system. Leave this setting on, as you want the fire to start when the scene starts playing.
  • Max Particles: The maximum amount of particles the particle system is allowed to have alive at any time. If you try to emit more particles than this once the system hits this limit, they won’t be emitted at all. This setting is used primarily for performance reasons; the default value of 1000 particles is more than enough in this case.

Whew, that was quite a list! But as a result, you’ve learned how to add a particle system to your scene and how to customize it to your liking.

Run your scene again to see the effect of your changes:

It looks a bit more like fire every time, doesn’t it? It needs more particles though, and to do that, you change the emission of the system.

Introducing the Emission Module

The Emission module is one of the most important modules in Unity particle systems; it handles the number and timing of emitted particles in the system to create a continuous flow or a sudden burst of particles depending on your needs.

While still in the particle system’s Inspector, click on the Emission module title:

This opens up the Emission module:

The Rate is the number of particles emitted per second (Time), or alternatively, per unit (Distance). You can switch between the two modes by clicking the combo box and selecting the desired mode:

Leave the settings at Time and change the Rate to 50.

Run your scene again; it looks a lot more lively now:

Yeah, it still looks like smoke. But here comes the biggest change so far in this tutorial: a custom texture!

Adding a Custom Texture

All particles have a particle material and a texture that defines how they look. There’s only so much you can do with the default texture. By changing the texture you can create effects like magic stars, smoke and of course, fire.

Changing the particle texture is quite easy. Up to now, the particles were drawn on the screen using the Default-Particle material, which is a particle material with a circular gradient texture:

To change the material, select the TorchFireParticles GameObject inside the Hierarchy. Then, find the the particle system component in the Inspector, and open up the particle system’s Renderer module.

Open the Materials folder in the Project View, and drag the FireMaterial Material to the Material property:

Finally, run the scene to see your custom texture in use:

Can’t you almost feel the heat? :] The flame’s a bit too wide though; to fix that, you’ll have to change the shape of the particle system.

Changing the Particle System’s Shape

The Shape module, as the name implies, controls the shape and the behavior of particles in that shape. You can choose from several different shapes; each has their own particular settings. This lets you create particles in a box, a sphere, or even in your own custom mesh!

Expand the Shape module in the Inspector:

The shape of your particle system is set to cone, which means particles emit from the base and are moved outwards at an angle:

In the example above the base is colored blue, the angle is green and the particles are red. Also notice that while you have the Shape Module expanded, you’re presented with a handy preview of the cone in the Scene view:

Changing the Angle changes the size of the cone to make it wider or narrower. Set this to 10; you’ll get a nice tight flame that widens slightly as the particles rise.

Changing the Radius changes the size of the base; the larger this value is, the more the particles will scatter as they emit. Set this value to 0.2; this ensures the flames will start inside the fuel holder of the torch.

Run your scene and see how the shape of the flame has changed:

That’s starting to look like a real flame! The finishing touch is to change the size of the particles over the course of their lifetime.

Changing Size Over Lifetime

With the Size over Lifetime module, you can create particles that grow or shrink during their lifetime, or even pulsate like fireflies in a forest.

In your particle system’s module list, look for “Size over Lifetime“. Contrary to the previous modules, Size over Lifetime isn’t enabled by default. Click on the checkbox next to the module name to enable it:

Expand the Size over Lifetime module by clicking on its name. This will display a dark gray background with a flat Curve running along the top:

Click on the dark gray background to open the curves editor at the bottom of the Inspector. The horizontal axis depicts the lifetime of the particle while the vertical axis depicts its size:

You can move the keys at either end of the red line to edit the curve; you can also add additional keys by double-clicking anywhere on the curve. To delete keys, right-click on the key to remove and select Delete Key:

You can also select one of the preset curves at the bottom:

If you think about flames in the real world, they tend to shrink as the particles rise, so select the third preset from the right to create a downwards slope:

Run your scene to see your effect in all its fiery glory!

If you’ve worked in a basic form with Animations, see if you can figure out how to add flickering shadows!

Solution Inside: How to create flickering shadows? SelectShow>

Congratulations! You’ve learned how to set up a new particle system and bend it to your will to make a beautiful fire effect. Take a break, get something to drink or eat to celebrate, then come back and let your inner Michael Bay shine as you learn to create explosion effects!

Building a Bomb (Effect)

Making an exploding bomb is quite simple using Unity. Once you know how to instantiate particles at will, you can use this effect for things such as car wheels sparking when they scrape the ground, or balloons that pop and shower confetti.

Open up the Bomb scene from the Project Window and play the scene:

There’s a floor at the bottom of the scene, but apart from that, there’s not much going on at the moment.

To spawn bombs, drag the Bomb Prefab to the Bomb Emitter:

DragBombPrefabToEmitter

Play the scene again to see your bombs appear:

The emitter creates a new bomb every 2 seconds. To put a neat spin on things, you’ll add some rotational force to the bomb when it spawns.

Open up the Bomb script inside the Scripts folder in your Project Window.

Add the following code to Start():

void Start() {
  float randomX = UnityEngine.Random.Range (10f, 100f);
  float randomY = UnityEngine.Random.Range (10f, 100f);
  float randomZ = UnityEngine.Random.Range (10f, 100f);
 
  Rigidbody bomb = GetComponent<Rigidbody> ();
  bomb.AddTorque (randomX, randomY, randomZ);
}

The first three lines generate random float values between 10 and 100 for the x, y and z axes. Next, you get a reference to the bomb’s Rigidbody component and apply torque to it. This causes the bomb to rotate in a random direction:

The bombs now rotate nicely while they fall — but you were promised explosions! Don’t worry; you’ll add that now. :]

In the Hierarchy, press the Create button and select Create Empty. Click on the newly created GameObject and name it ExplosionParticles. Next, add a new particle system to the GameObject. If you’ve forgotten how to create a particle system, scroll on up for a refresher.

With your particle system in place, drag the ExplosionParticles GameObject from the Hierarchy to the Prefabs folder in the Project Browser. Next, select the Bomb Prefab inside the Prefabs folder. Finally, drag the ExplosionParticles Prefab to the Bomb‘s Explosion Particles Prefab slot like so:

Now, when a bomb touches the ground a new Explosion Particles GameObject will spawn.

Play your scene to see how the explosion looks:

Very…uh…magical, but nothing near an explosion yet! Also notice there’s already an ExplosionParticles GameObject present in the scene at the start. Delete the ExplosionParticles GameObject in the Hierarchy; from now on you’ll be editing the prefab.

As with the torch, you’ll be using the fire material for the particle system.

Select the ExplosionParticles Prefab in the Project Window, then expand the Renderer Module in the Inspector. Drag the FireMaterial from the Materials folder in the Project Window to the Material slot as shown below:

To complete the effect, you’ll have to modify the following settings in the Main module:

ExplosionMainModule

  1. Set the Duration to 0.70.
  2. Looping should be disabled. The particles should emit just once.
  3. Set the Start Lifetime to 0.7.
  4. Set the Start Speed to 10.
  5. Set Start Size to 2.
  6. Set the Gravity Modifier to 1. This will make the particles drop slightly at the end.

Run your bomb scene to see what you’ve built:

Well, it’s kind of explod-y, but you can definitely do better!

Building the Explosion

To improve the explosion, you’ll alter the properties of one particle system’s modules. Can you guess which module to alter? Here’s a hint — you’ve already used it.

If you guessed the Emission module, give yourself a pat on the back!

Expand the Emission Module; as you saw earlier, the Rate is the number of particles spawned per second. For this explosion, you won’t want a steady flow of particles, but rather a sudden burst.

Set the Rate to 0. Now take a look beneath the Rate; there’s a list of Bursts that’s empty by default:

A Burst is a collection of particles emitted all at once at a particular point in time.

Click on the + button at the bottom right to add a new Burst. You’ll see two fields: Time & Particles:

Leave the Time at 0, and set Particles to 150.

These settings will make the particle system emit 150 particles all at once at the start of the system.

Play your scene; how do things look now?

Now THAT looks more like an explosion! While this explosion looks better, the shape is still an awkward cone and the particles don’t fade out — they just disappear. You’ll need to mold your explosion to give it that final touch.

To get started, expand the Shape Module:

You’ve already used this module for the torch’s fire shape, but there are several more shapes to choose from. Click on the dropdown box that says Cone to see all options available to you:

Each shape affects the emitter in a different way. Each animation below shows the same emitter, with only the shape changed:

Sphere

HemiSphere

Cone

Box

Mesh (Cube)

Circle


Edge

You can get lots of different effects from the same system — just by changing the shape!

To create a realistic explosion, set the shape to Sphere.

Run the scene and prepare to be blown away:

Now that looks awesome! :]

While the explosion looks good, there’s one small problem. The particles just disappear. This is a jarring effect and doesn’t look natural at all. Rather than just disappear, the particles should disappear over time to make the explosion fade away.

Changing Color

With the particle system open in the Inspector, click the checkbox next the Color over Lifetime module to enable it and expand it. You’ll be greeted by the word Color and what looks like a white block next to it. Click on the white block:

Screen Shot 2015-10-30 at 2.16.41 PM

This opens up the gradient editor:

The color change over the lifetime of the particles is represented as a gradient bar. The starting color is on the far left, and the particles will transition to the color on the right side:

The four white arrows at the edges are known as markers; click between two existing markers to add a new one. To remove a marker, drag it off the bar:

The top markers handle the Alpha or opacity of the color, while the bottom markers manage the RGB (Red, Green, Blue) color values.

Click on the rightmost alpha marker. The bottom of the Gradient editor now shows the current alpha value:

Drag the slider all the way to 0. Now the particles will gradually fade away over the course of their lifetime.

Run your scene once again to see the effect of your changes:

Yeah baby — that’s one hot explosion!

Want extra credit? Return to the torch scene and configure the flame to use Size Over Lifetime Module to achieve a similar effect.

Where to Go From Here?

You can download the final project here.

In this tutorial, you’ve learned how particle systems and its various modules work in Unity, and how to tweak them to get exactly the effect you want. Feel free to experiment with the different settings to see what other cool effects you can achieve.

For more information on the Shuriken Particle System and its modules, take a look at Unity’s official documentation and their Particle System video.

I hope you enjoyed this tutorial; if you have any comments or questions, please share them in the discussion below!

The post Introduction To Unity: Particle Systems appeared first on Ray Wenderlich.

Video Tutorial: Beginning Native tvOS Apps Part 5: Top Shelf


Video Tutorial: Beginning Native tvOS Apps Part 6: Conclusion

Introduction to Unity UI – Part 1

$
0
0
Note: This tutorial is part of the Unity Feast. To see more tutorials being featured in the Unity Feast as well as to learn how to take part in the Unity Feast game jam, click over here.

Update 11/20/15: This tutorial was updated to Unity 5.2 by Pedro Pereira & Orlando Pereira. Original post by tutorial team member Kirill Muzykov.

You will love getting gooey with Unity’s new GUI!

You will love getting gooey with Unity’s new GUI!

In previous versions of Unity, the old UI system was downright horrific. It required you to write all your GUI code in OnGUI. It was very programmer-centric which goes against the visual centric nature of Unity itself, and not mention slow and inefficient.

Thankfully, the folks over at Unity Technologies have listened.

In this three-part series, you’re going to explore Unity’s new UI system by adding an interactive UI to a small game named Rocket Mouse.

To add a little spice and satisfy your users’ cravings for an engaging UI, you will also:

  • Animate the buttons;
  • Create a settings dialog that slides into the scene;
  • Use more GUI controls like Text, Slider, Panel, Mask and so on;

If you want a sneak peak, just download and run the RocketMouse Final to see what you’ll learn from this tutorial. :]

Getting Started

You will need some images for backgrounds, buttons and other UI elements, as well as a few fonts for the labels and buttons. And no, you won’t have to draw anything yourself or scour the web for the right assets because I’ve prepared a special package that has everything you need. You’re welcome. :]

Note: Keep in mind that this tutorial does not cover the creation of the game itself. The goal here is to provide an introduction to the new Unity UI system and familiarize you with its components.

You can download the package here: RocketMouse_GUI_Assets.

Within the package you will find background images, buttons, icons and other game art, in addition to two fonts from dafont.com. You can thank Rodrigo Fuenzalida for the Titan One font and Draghia Cornel for the DCC Dreamer font.

Lastly, you’ll need to download the starter project containing the RocketMouse game. Download and unpack the Rocket Mouse project using the following link: RocketMouse_Starter.

This is all you need! Well, except love, if you take the Beatles song to heart. :]

Creating MenuScene

Open the RocketMouse_Starter project in Unity by selecting OPEN within Unity’s startup dialog and specifying the root folder of the project.

Open_Project

You’re going to spend most of your time working with a new scene that you’ll create now. From menubar, Select File\New Scene to create a new empty scene.

It’s better to save the scene straight-away, so open the Save Scene dialog by choosing File\Save Scene. Then, enter MenuScene as the scene name and save it to the Scenes folder, right next to the RocketMouse scene.

03

Take a look at the Project Browser to confirm that there are two scenes in one folder.

04

Importing Images and Fonts

First on your to do list is to add assets to the scene, so unpack the assets package. There you’ll find two folders: Menu and Fonts.

Select both folders, and then drag them to the Assets folder in Unity’s Project Browser.

Allow a few seconds for Unity to process the files. Then you should see a Fonts folder and a Menu folder in the Project Browser as shown below.

05

Woo-hoo! You’ve finished the setup and you are ready to create your first UI element using the new Unity GUI system.

Adding your First UI Element

The first element you’ll make is the background image for the menu scene.

From the menubar, select GameObject/UI/Image. This adds an object named Image to the scene. You should see it in the Hierarchy as a child of Canvas. All elements must be placed on a Canvas, so if you don’t already have one, Unity will provide one for you.

To ensure you can see the image in the scene view, select Image in the Hierarchy and set both its Pos X and Pos Y to 0.

06

Note: The Rect Transform is the component used to position UI elements within a Canvas. You will be working with it frequently throughout this tutorial as you use it to position the UI elements in the Menu scene.

You’ll set the correct position and size in a moment – right now, there is another interesting thing to muse upon. Look carefully in the Hierarchy, and you’ll see there are three new objects in the scene:

  1. Image
  2. Canvas
  3. EventSystem

07

The Image is a non-interactive control that displays a Sprite texture and has many options to tweak.

For instance, you can apply a color to the image, assign a material to it, control how much of the image that displays, or even animate how it appears on the screen using a clockwise wipe.

The Canvas is the root object for all your UI elements and, as previously stated, it’s created automatically when you add your first UI element. It has multiple properties that allow you to control how your UI renders, and you’ll explore some of them during this tutorial.

The EventSystem processes and routes input events to objects within a scene. It is also responsible for managing raycasting. Like the Canvas, it is required for the UI to work so it is also added automatically.

Setting Up the Menu Background Image

The first thing to do is rename your image. In the Hierarchy, select Image and rename to Img_Background.

Next, open the Menu folder in the Project Browser and find the menu_background image. Drag it to the Source Image field of the Image component in Img_Background in the Inspector.

08

Now you have a background image instead of the default white image. However, it doesn’t look like a good background because it’s too small and the aspect ratio is incorrect.

To fix, find the Set Native Size button in the Inspector and click it to set the size to 1136 x 640.

09

Now it looks like a proper background.

10

However, there is still one issue:

  • Shrink your Scene view, and you’ll see the Canvas (the white rectangle) covers only part of the image. If you switch to the Game view, you’ll see only a part of the background image, as if the camera is too close to the image to capture it completely.

11

Note: The original game was designed for iPhones with 3.5- and 4-inch displays. This is why all the game art supports 1136 x 640 and 960 x 640 resolutions. You will soon see how the UI can adapt to different game resolutions.

You’ll tackle this issue by using a Canvas Scaler.

Using the Canvas Scaler

You will use the Canvas Scaler to adjust the way the background image displays.

First, however, you need to know that the display is not the result of a bug. From Unity’s point of view, you have the Game view — or viewport — set to such a small size that it just displays a portion of the image that fits within the Game view.

If you were to run the game on a device with a large enough resolution or simply stretch the Game view to fit the whole image, you would see the entire background image.

Although Unity’s settings make sense in most scenarios, there are times when you need different behavior. An example is when you have a small monitor that doesn’t fit your target device’s resolution.

Additionally, many games support only one resolution. Designers use this reference resolution to dictate sizes, positions, and other data. When you develop a game based on a single reference resolution, you want to make sure to enter the designer’s specifications without additional calculations so that the user sees everything exactly as intended.

If you’ve ever ignored your designer’s directions, surely you know there’s a price to pay. Really though, the user’s experience and the varying resolutions out there are more important, but you have to keep your designer happy, too. :]

Fortunately, a special component comes to the rescue. This component is called Canvas Scaler and you will find it attached to every Canvas.

Select Canvas in the Hierarchy, and in the Inspector, you should see the Canvas Scaler component.

12

The Canvas Scalar has three modes:

Constant Pixel Size: Makes all the user interface elements retain the same pixel size, regardless of the screen size. This is the default value of the Canvas.

Scale With Screen Size: User interface elements are sized and positioned in accordance to a referenced resolution. If the current resolution is larger than the referenced resolution, then the Canvas will maintain the reference resolution, while scaling up the elements to match the target resolution.

Constant Physical Size: Positions of the user interface elements are specified in physical units such as millimeters or points. This requires the correct reporting of the screen DPI.

Change the component mode to Scale With Screen Size. Set its Reference Resolution to 1136 x 640. Also, slide the Match Width or Height all the way to the right, or simply enter 1 in the input field.

13

After making those changes, you’ll immediately see the full background image, even in a small Game view window.

14

Change the Game view resolution to see how your game might look in a different resolution, for example on iPhone Wide 480×320. Nice. It still looks good!

Note: If you don’t see any of the iPhone options, then chances are, you are building for a different platform. From the menubar, select File\Build Settings. In the build settings dialog underneath the platform settings, make sure to select iOS.

Screen Shot 2015-11-17 at 3.59.31 PM

Unity will reprocess all your assets so it may take awhile. At the end, you should now have access to the various iOS screen sizes.

15

Now switch to the Scene view, and you’ll see the Canvas’s size doesn’t change when you resize the Scene view.

As you can see, the side edges of the screen are neatly cropped, while the central part is fully visible. This is the result of setting Match Width or Height to 1 (match height). It works perfectly for your target resolutions.

And that’s how you manage your designer’s instructions for the background and your users’ many potential resolutions.

But what about the buttons? What happens when they’re very close to the left or the right edge of the screen? You sure don’t want to crop or hide them.

Fortunately, Unity has a feature that will help you sidestep this rookie error. You’ll learn about it soon.

Adding a Header Image

It might have seemed a bit time consuming to add the background image, but that’s mostly because you were setting up the initial UI. Plus, after doing this a couple of times you’ll find the setup to be so fast and easy that you’ll barely have time to blink before you’re done.

Before moving on to buttons and other UI controls, you’ll add one more image — the header image. For this exercise, you’ll use a non-fullscreen image to demonstrate a few other important concepts of Unity’s new UI system.

Open the Scene view and from the menubar, select GameObject\UI\Image. This will add another image somewhere within the scene. Here’s where it ended up for me:

16

Note: Should the image in end up in the hinterlands, just set its Pos X and Pos Y properties to 0.

Now, turn that white rectangle into an actual image by following these steps:

  1. Select Image in the Hierarchy and rename it to Img_Header.
  2. Open the Menu folder in the Project Browser and search for the header_label image.
  3. Drag this image to the Source Image field on the Inspector.
  4. Click Set Native Size in the Inspector.

17

As you can see, it was easy enough to add another image. Now you just need to work on the positioning, which brings you to your next exercise: working with the Rect Transform component.

Rect Transform, Anchors, Pivot and You

If you worked with Unity before, or at least completed some Unity tutorials on this website, then you’ve probably had some exposure to the Transform component.

If not, that’s fine too. It’s simply a tool that can position, rotate and scale objects in a scene. Here’s what it looks like:

18

You will see the Transform component when you select any type of non-UI GameObject in your Hierarchy view.

19

However, if you select any UI element, for example Img_Header, you’ll see a different component named Rect Transform.

20

As you can see, Transform and Rect Transform look a bit different. Additionally, the Rect Transform can change the way it looks, depending on its Anchor settings. For example, it can look like this:

21

Here, instead of Pos X, Pos Y, Width and Height, you have Left, Top, Right and Bottom.

Are you wondering about the Anchors setting that changes the look of Rect Transform so dramatically? You’ll find the answers you seek in the next section.

Anchors

Setting Anchors is a simple, elegant and powerful way to control the position and size of your UI elements, relative to their parent. It’s especially handy when you resize the parents.

When you set Anchors, you specify several positions in the parent, usually one in each corner of the parent’s UI element Rect. When the parent is resized, your UI element will try to maintain a uniform distance to the anchor points, thus forcing it to move or resize right along with its parent.

To see different Anchor Presets just select Img_Header in the Hierarchy and click on the rectangle right above the Anchors field in the Rect Transform component.

22

After clicking, you’ll see various Anchor Presets: these are the most common settings for Anchors. However, you are not restricted to them and you can customize any of them. You can also select different horizontal and vertical behavior for your UI element.

This will all make more sense once you work with it. If you look at the next image, which has the background image disabled, you’ll be able to see the Canvas size changes a bit better.

As you can see, the Anchors settings control how your UI element adapts to screen size changes.

23

I’m sure you want to try some different settings to understand how they work, but before you do be sure to at least read through the next section. It’ll help you understand Anchors a little better so that you can get more out of your experimentation.

Anchors Manipulator

Currently, the Anchors shown use 4 triangles. Here is how it looks with Anchors set to the top-center preset:

24

Custom Anchors

You can manually move Anchors to a custom position as the presets are entirely optional — they are just for your convenience.

Note: You might find yourself in a situation where the translation gizmo covers the anchor icon, making it impossible to select the anchor.

In this case, just select the anchor icon by choosing an anchor preset (for example, the left-hand side of the screen). The anchor icon will shift to that part of the screen, allowing you to select and move it at will.

25

Note: See how the image moves to the right when you resize the Canvas? However, it moves only a little in relation to the right edge of the Canvas. This happens because Anchors are set to 25% width of the Canvas.

Splitting Anchors

You can split Anchors to make them stretch a UI Element horizontally, vertically or in both dimensions.

26

Note: You’re not actually resizing the Canvas when dragging one if its edges. In fact, you can’t resize the Canvas this way.
Look for the word Preview next to the cursor when you try to resize it. Use this technique to experiment and see how your UI elements adapt to different screen sizes.
27

Rect Transform Depends on the Current Anchors Setting

Depending on the Anchors setting, the Rect Transform provides different ways to control the size and position of your UI element.

If you set Anchors to some single point, without stretching, you’ll see Pos X, Pos Y, Width and Height Properties.

However, if you set Anchors in a way that stretches your UI Element, you’ll get Left and Right instead of Pos X and Width (if you set it to stretch horizontally) and Top and Bottom instead of Pos Y and Height (if you set it to stretch vertically).

In this screenshot, Img_Header’s Anchors are set to middle-stretch. This means that the image stays in the middle of the Canvas vertically and stretches horizontally.

28

Pivot

There is one final property to discuss in the Rect Transform component, and this is Pivot.

The Pivot is a point around which all transformations are made. In other words, if you change your UI Element position, you also change the pivot point position. If you rotate your UI Element, it’ll rotate around that point.

The Pivot is set in normalized coordinates. This means that it goes from 0 to 1 for both height and width where (0,0) is the bottom left corner and (1,1) is the top right corner.

Note: You can also set Pivot outside the UI Element bounds. In this case, Pivot will be outside (0,0) – (1,1) range. This can be useful. For example, you might want to rotate your object around some point in the scene. To alter the pivot, you must make sure the Pivot/Center button is toggled to Pivot like so:
29

You can change Pivot in the Rect Transform component in the Inspector or you can use the Rect Tool.

30

Take a look at the following two images that demonstrate the UI Element with the same Pos X and Pos Y values, yet each shows different placement in the scene.

The first image shows Pivot at its default value of (0.5 , 0.5), which is the center of the UI element. The Position is set to (0, 0) and Anchors are set to top-left.

31

Note: It’s important to understand that the position of a UI Element is set relative to the Anchors. This is why (0,0) position means the distance from Anchors, which are set to top-left corner of the Canvas.

Now take a look at the second image. As you can see, the position is unchanged at (0,0), but since the Pivot is set to left bottom corner (0,0) you can see that the image’s bottom corner, and not the center, is now placed at the Canvas’s top-left.

32

It’s harder to show how Pivot affects rotation and size using a still image, so here are few animations:

33

Observe how the image rotates around the pivot point indicated by a blue circle, which is an element you can freely move.

34

Note: Hold the ALT key while scaling to scale around the pivot point.

As you can see, Pivot also affects how your UI Element resizes.

Note: Another important thing to understand is that when you change the size of a UI Element, you don’t change its Scale. Instead, you change its size using Width and Height or Top, Right, Left, and Bottom paddings.

Be aware that there are a few differences between size and scale. For example, size can’t be negative, but scale can be. Also, using a negative scale value will flip your UI element. In most cases, you should only change the size of your UI Elements.

Placing a Header Image

Phew! That was quite a few words dedicated to Rect Transform, Anchors and Pivot. Believe me, you’ll be grateful you spent the time working through the exercise, as understanding them is essential to awesome UI in your games.

Going forward, you’ll concentrate on actually creating the menu scene. The rest of the sections will go by in the twinkle of an eye.

All those manipulations completely exhausted the poor little img_header. It’s time to place it where it should be and leave it alone to recover.

35

Before you continue, re-enable Img_Background if you disabled it to see the Canvas border.

Then select Img_Header in the Hierarchy and set its properties in the Inspector as follows:

  1. Click Set Native Size to reset the size, as you probably messed with it while playing around with Pivot.
  2. Set Anchors to top-center.
  3. Set Pos X to 0 and Pos Y to -100.

36

You should see something like this in your Scene view:

37

That’s it! Now, leave the header image alone. It’s a little tired, too. :]

38

Adding the Start Button

Now, that your app has a nice background with a label, it’s time to add some buttons.

From the menubar, choose GameObject\UI\Button. This will add a Button object to the scene, you should see it in the Hierarchy. If you expand it in the Hierarchy, you’ll see that the button contains a Text element — you’ll learn about these later.

39

Look at the button in the Inspector, and you’ll see it has a familiar Image (Script) component, the same as you used to add the background and the header label.

Additionally, there is a Button (Script) component. In other words, a button is just an image with a child Text element and an attached button script.

Note: The Text element is optional, so if you have a button image with text drawn right into the image, you can delete it. You’ll do this a couple of times during this tutorial.

Positioning the Button

Now it’s all about positioning and resizing the button. Follow these steps:

  1. Select Button in the Hierarchy view and rename it to Btn_Start.
  2. Set its Anchors to bottom-stretch, since you want it to stretch horizontally if the screen size changes.
  3. Set both Left and Right to 350.
  4. Set Height to 80.
  5. Set Pos Y to 300.

40

Then select the nested Text element and set its Text to Start Game. Change the Font Size to 32 to make the text of the button larger.

41

This is what you should see in the Scene view:

Screen Shot 2015-11-17 at 4.28.15 PM

Well…you definitely have a button now, that’s for sure, and it’s in need of a facelift. To make the button look good, you’ll set an image as its background and then use a fancier font.

9-Slice Scaling

You set the image for the Button the same way you set an image for the Image. After all, they use exactly the same component. However, unlike images that rarely scale, especially non-uniformly, buttons often come in completely different sizes.

Of course, you could create a background image for every single button size in your game, but why waste all that space? You’ll use a technique called 9-Slice scaling, which allows you to provide one small image that scales to fit all the sizes.

No, there is no magic involved. You won’t have to put your images in a magic fountain before you can use them :]

This technique works by creating different images for each of nine zones, all of which scale differently.

43

This ensures the image will look good at any scale.

Preparing Button Images

Before you can use a sliced image, you need to set those 9 zones. To do this, open the Menu folder in the Project Browser and select btn_9slice_normal image.

In the Inspector’s Import Settings, set Format to Truecolor and then click on the Sprite Editor button to open the Sprite Editor view.

44

Note: Setting Format to Truecolor is not required and not related to image scaling. However, I experienced compression artifacts with my set of images, so I found that it’s better to do this. If you use your own images and they look good in the compressed format, then you don’t need to tinker with this setting.

In the Sprite Editor, set the Border values to L:14, R:14, B:16, T:16. Remember to click Apply!

45

Repeat the same process for btn_9slice_highlighted and btn_9slice_pressed images, which you’ll use for different button states.

Setting Button Images

After preparing all images, you only need to drag them to the corresponding fields in the Inspector. Select Btn_Start in the Hierarchy and follow these steps:

  1. Change Image Type to Sliced in the Image component.
  2. Change the Transition property in the Button component to SpriteSwap.
  3. Drag btn_9slice_normal to Source Image in the Image component.
  4. Drag btn_9slice_highlighted to Highlighted Sprite in the Button component.
  5. Drag btn_9slice_pressed to Pressed Sprite in the Button component.

46

Note: If you encounter this error message, This image doesn’t have a border, then you probably forgot to set the Border in the Sprite Editor in the Import Settings as described above.
47

Before running the scene and enjoying your cool buttons you are going to take a few seconds to change the font used by the nested Text label. This will make the button mega-awesome.

Setting a Custom Font for the Button

Using a custom font is easy. Remember the Fonts folder in the package you downloaded and added to the project? Now it’s time to break it out and use one of those fonts.

Select the Text element nested within Btn_Start in the Hierarchy. Then open the Fonts folder in the Project Browser and drag the TitanOne-Regular font into the Font field. Also set the Color to white.

48

Now run the scene and enjoy your new mega-awesome button! :]

Screen Shot 2015-11-17 at 4.37.36 PM

Adding the Settings Button

There are only few things left to do before moving on to the next part, and one of them is adding the Settings button.

You can probably do this yourself, so you’re only getting the size and position of the button to start. The rest is almost identical to how you created the Start Game button.

Note: The easiest way is of course to duplicate the button and adjust some properties, but try creating the button from scratch since you’re here to learn.

So, here are the properties of the Settings button that are different:

  • Name: Btn_Settings
  • Rect Transform: Left and Right are 450, Height is 70 and Pos Y is 180
  • Text: Settings
Solution Inside: Solution Inside: Need help creating the Settings button? SelectShow>

This is what you should see in the Scene view after adding the Settings button:

52

Starting the Game

The final task for this part is to actually click the Start Game button and run the second scene in the game itself.

Adding Scenes to Build

Before you can run different scenes, you need to add them to the Scenes in Build list in the Project Settings, so that they are included in the final application.

To do this, on the menu select File\Build Settings. This will open the Build Settings dialog. Then open the Scenes folder in the Project Browser and drag the MenuScene first, and then the RocketMouse scene to the Scenes in Build list.

53

Finally, close the Build Settings dialog.

Creating UIManager

When you add an event handler to the button, you need to specify which method to call when you tap the button. Since you cannot use static methods, you will need to select a public method from a script that is attached to a GameObject.

From the menubar, choose GameObject\Create Empty. Then select GameObject in the Hierarchy view and rename it to UIManager.

After that, click Add Component in the Inspector and select New Script. Name it UIManagerScript. Make sure the Language is set to CSharp and click Create and Add.

This is what you should see in the Hierarchy view and the Inspector view:

54

Double-click on the UIManagerScript in the Inspector to open the script in MonoDevelop. Once the script loads, remove the Start and Update methods, and add the StartGame method as follows:

public void StartGame() {
    Application.LoadLevel("RocketMouse");
}

Save the file and make sure it contains no errors by building it within MonoDevelop. Selecting Build\Build All in MonoDevelop’s menu will accomplish this.

Calling the StartGame method when the Player Clicks the Button

Switch back to Unity and follow these steps:

  1. Select Btn_Start in the Hierarchy and scroll down in the Inspector to the On Click() list.
  2. Click the + button to add new item.
  3. Then drag UIManager from the Hierarchy to the newly added item in the list.
  4. Click on the dropdown to select the function. Right now, it’s set to No Function.
  5. In the opened menu select UIManagerScript\StartGame ().

55

Run the scene and click the Start Game button, this should open the game scene.

Where to go From Here?

Stuck on any issues? Feel free to download the completed project for this part.

It might feel like you didn’t do much in this last section but this is not true. You set up the UI, added images and buttons, and even wrote the code that starts the game when you click on the button!

In many games, that’s all that comprises the UI.

You also learned a lot about Rect Transform, Anchors, Pivot and so on. What’s cool is now that you understand them, you’ll be able to move much faster when you apply these new skills to your own projects. You can download the completed project here.

In the next part of this series, you’ll learn how to animate UI elements, create dialogs, and use controls like Slider and Toggle. By the end of it you’ll have a working menu scene.

If you have any questions or comments please leave them below! See you in Part 2!

The post Introduction to Unity UI – Part 1 appeared first on Ray Wenderlich.

Introduction to Unity UI – Part 2

$
0
0
Note: This tutorial is part of the Unity Feast. To see more tutorials being featured in the Unity Feast as well as to learn how to take part in the Unity Feast game jam, click over here.

Update 11/20/15: This tutorial was updated to Unity 5.2 by Pedro Pereira & Orlando Pereira. Original post by tutorial team member Kirill Muzykov.

Learn to add some animation to your UI.

Learn to add some animation to your UI.

Welcome back! In part 1 of this three-part tutorial series, you created a nice scene with two buttons. You learned how to use the Image, Button and Text UI controls, as well as concepts such as Anchors and Pivot. However, the scene itself is pretty simple and in need of an upgrade.

In this tutorial, you’ll spruce up the scene by adding animations, a settings dialog and more UI controls like the slider and the toggle. If you don’t have the project already, download it here.

So, go ahead and open the project in Unity. Open the MenuScene, grab an invigorating beverage and start thinking UI!

Animating Buttons

You’re going to jump right into the exercises by adding some cool animations. There are several reasons for that. First — animations are cool! Second, they’re practical for this project. You need the buttons to exit from the scene so that there will be enough space to display the new dialog that you’ll create later.

Creating Animation and Animator

Animating buttons is no different from animating any other Unity object. You’ll need to add an Animator component, create a few animations and set up states and transitions between them.

Here are the steps to success:

  1. Select Btn_Start in the Hierarchy
  2. Open the Animation view.
  3. Click on the Create button in the Animation view. This will create the Animator and an animation clip.
  4. 01

  5. Name the animation btn_start_slide_out and save it in the Animations folder.

02
In addition to creating the animation itself, Unity also kindly adds an Animator component to btn_start and creates an Animator Controller.

03

Animating a Button Sliding Out of the Screen

Although you’ll technically make two animations — the button slide out and then the slide back in — you’re going to be a savvy developer and create one, and then reverse it.

To create the slide-out animation, follow these steps:

05

  1. Select Btn_Start in the Hierarchy
  2. Make sure the Animation view is visible.
  3. Click on the 1:00 mark in the timeline and make sure animation recording turns on. It should do this automatically.
  4. Note: The easiest way to make sure recording is on is to take a look at the playback controls and watch for them to turn red.
    04

  5. Change Anchors to top-stretch.
  6. Change Pos Y to 60 in the Inspector.
  7. Stop the recording by clicking the red circle button.

A: A keyframe was inserted automatically at the 0:00 mark. At this point, the button is at its starting position, precisely where you positioned it in the previous tutorial.

B: Although the anchors’ visual representation didn’t turn red, you can see the numeric values changed and turned red, indicating that you’ve also animated the anchors.

Make both the Animation view and Scene view visible and play the animation. You’ll see something like this:

06

Did you notice the animation on the anchors? If not, surely you noticed that annoying blinking red arrow.

Anyways, why do you need to reposition anchors?

Well, when you think about it this way, it’ll be obvious: the position of the button is the distance to its anchors. In the case of btn_start, it was the distance from the bottom edge. Right now, you’re only working with vertical movement, so only the bottom edge matters.

To make sure the button “leaves” the screen, you move it up until it’s no longer visible. What do you do if you don’t know the height of the screen? How do you make sure the button stops right after it’s no longer visible?

The answer is by changing its anchors.

If you set the anchors to the top edge of the screen, you simply set set the distance from the top edge of the screen. Thus, the button will always be above the edge and independent from the height of the screen, since it’s positioned relative to the screen’s top edge.

Animating Button Slide In

Nice work! You have a button that slides out of the screen, and now you need a reverse animation. You’ll use it in two cases:

  1. When the scene loads, you want the button to slide into position instead of simply appearing.
  2. When you close the settings dialog, the buttons should return to their initial positions

It’s quite easy to do. First, you need to disable looping of the animation, since the button should move either up or down and then stop instead of moving back and forth like a ping-pong ball.

To disable looping, open the Animations folder in the Project Browser and select the btn_start_slide_out animation. In the Inspector, uncheck Loop Time.

07

Then select Btn_Start in the Hierarchy and open the Animator view. Right-click on the btn_start_slide_out state and select Copy.

Screen Shot 2015-11-18 at 1.20.11 PM

Then right-click somewhere on the free space inside the Animator view, and select Paste. This duplicates the btn_start_slide_out state.

Screen Shot 2015-11-18 at 1.22.01 PM

Now, select this duplicated state, likely called something like btn_start_slide_out 0, and rename it to btn_start_slide_in in the Inspector. Additionally, set Speed to -1.

Screen Shot 2015-11-18 at 1.25.33 PM

Then, inside the Animator view, right-click on the btn_start_slide_in and select Set As Layer Default State, since you want the button to start its lifecycle by sliding into the screen and not vice-versa.

Screen Shot 2015-11-18 at 1.27.29 PM

Next, you need a parameter to control the state of the button. In the left hand column of the Animator window, click the Parameters tab. Next, Click the + button and add new Bool parameter named isHidden.

Screen Shot 2015-11-18 at 1.32.11 PM

Finally, add two transitions between the states. To do this, right-click on the btn_start_slide_out state and select Make Transition. Then click on the btn_start_slide_in to make a transition.

After that, create a reverse transition by right-clicking btn_start_slide_in, selecting Make Transition and then clicking on the btn_start_slide_out. This is what you should get in the end:

Screen Shot 2015-11-18 at 1.35.55 PM

You’re close, but you still need to assign a value to isHidden based on which transition is occurring.

Select the transition from btn_start_slide_out to btn_start_slide_in. In the Inspector, click the + in the Conditions panel. Set isHidden to false.

Screen Shot 2015-11-18 at 8.05.39 PM

Then select the transition that goes in opposite direction, from btn_start_slide_in to btn_start_slide_out and set its Conditions to be isHidden equals true.

Screen Shot 2015-11-18 at 8.08.30 PM

Run the scene. You should see your button sleekly sliding in. Then change isHidden manually to make the button slide back.

play4

Note: Occasionally, I’ve encountered a problem during testing when manually switching isHidden — the button jumped to its start/stop position. However, everything worked perfectly fine when I changed the parameter within the code.

So if you’re experiencing problems, there’s no need to pound your fist on the desk. Just wait until you add the required code, which you’ll do soon.

Animating the Settings Button

The Settings button should slide down the screen to make some space in the center for the dialog.

Do you think you can animate the settings button yourself? All you need to know is:

  • Offscreen Pos Y should be -50
  • You don’t need to change Anchors, since the button is already positioned relative to the bottom edge of the screen.

Give it a try on your own. If you need a nudge, feel free to sneak a peek into the spoiler below.

Solution Inside: Animating Settings Button SelectShow>

This is what you should get in the end:

settingsfly

Well, it’s nice to see the Settings button going up and down, but shouldn’t both buttons slide out simultaneously, just as they slide in at the start?

Of course they should, and you’re going to make that happen next.

Triggering Buttons Animation from the Script

In MonoDevelop, open the UIManagerScript that you created in Part One, and add the following instance variables just inside the class definition:

public Animator startButton;
public Animator settingsButton;

After that, add following method:

public void OpenSettings() {
    startButton.SetBool("isHidden", true);
    settingsButton.SetBool("isHidden", true);
}

That is the all code you need. Save the script and switch back to Unity.

In Unity, select UIManager in the Hierarchy. Drag Btn_Start from the Hierarchy to the Start Button field in the Inspector and drag Btn_Settings to the Settings Button field.

18

Then select Btn_Settings in the Hierarchy and click + in the On Click() list. Drag UIManager from the Hierarchy to the new item in the list. After that, open the function selection menu and select UIManagerScript\OpenSettings ().

19

Run the scene. Wait for the buttons to stop moving and click on the Settings button. You should see both buttons move out of the screen in opposite directions simultaneously.

20

Adding the Settings Dialog

Look at all that gorgeous free space you created! That seems like the perfect place for a dialog to slide in there and fill the empty space. After all, nature abhors a vacuum :]

Creating the Panel

Usually, dialogs contain some other controls that should appear and move with dialog. Hence, it’s effective to create the dialog as a panel and set other UI Elements as child objects.

To create a panel, select GameObject\UI\Panel in the menu. This will create a full-screen panel that uses a white, semi-transparent image as a background. So, you should see some kind of full-screen veil.

21

However, this dialog won’t be full-screen; in fact, it will be relatively small. Follow these steps to set the dialog’s size and position:

  1. Select Panel in the Hierarchy and rename it to Dlg_Settings.
  2. Set its Anchors to middle-right, since you’ll position the dialog beyond the right edge and off the screen, so that it’s not visible when you run the scene.
  3. Set Width to 400 and Height to 150.
  4. Set Pos X to 220 and Pos Y to 0.

22

You should see a semi-transparent rectangle to the right of the canvas rectangle. All UI elements outside this rectangle are not visible on the screen. This is precisely what you want for the dialog!

Setting the Dialog’s Background Image

You’re going to use a 9-slice image as the dialog’s background, so you need to set the border in the Import Settings first.

Open the Menu folder in the Project Browser and select settings_panel_bg_9slice. In the Inspector, click Sprite Editor to open the Sprite Editor view.

Set all Border values to 20 and click Apply at the top.

23

Now you can use this image as the dialog background.

Select Dlg_Settings in the Hierarchy and drag settings_panel_bg_9slice to the Source Image field in the Inspector. Double-click on Color right next to the Source Image field, and set A to 255 to remove transparency.

24

This is how the dialog should look like after you set the background image:

25

Adding the Label

In its present state, it’s difficult to argue that the nondescript, green rectangle is actually a settings dialog, but there’s an easy way to fix this — all you need to do is to write “Settings” on it. Poof! Whoosh! Magic. :]

Select GameObject\UI\Text to create a new Text UI element. Select Text in the Hierarchy and rename it to Lbl_Settings. Then drag Lbl_Settings over Dlg_Settings to add it as a child object.

26

After that, select Lbl_Settings in the Hierarchy and make following changes:

  1. Set Anchors to top-center.
  2. Set Pos X to 0 and Pos Y to -40.
  3. Change Text to Settings.
  4. Open the Fonts folder in the Project Browser and drag the DCC – Dreamer font to the Font field in the Inspector.
  5. Set Font Size to 30.
  6. Set Alignment to Center Align.
  7. Set Color to White, with A (Alpha) 255 to remove transparency.

27

Animating the Settings Dialog

Now you’ve got a legitimate Settings dialog, and the next step is to make it appear when the user clicks the Settings button.

You’re going to use almost exactly the same technique as you did to make the buttons slide in and out, the only difference being that the dialog won’t slide in automatically after the scene starts.

Select Dlg_Settings in the Hierarchy and open the Animation view. Then create a new animation by clicking on the Create button in the Animator.

Name the animation dlg_settings_slide_in and save it in the Animations folder.

29

Then click on the 1:00 mark in the timeline and make sure recording is started, or start it manually by clicking the record button.

30

In the Inspector, set Anchors to middle-center and Pos X to 0.

31

Stop recording the animation.

32

Open the Animations folder in the Project Browser and select dlg_settings_slide_in. In the Inspector, uncheck Loop Time.

33

Now, switch to the Animator view. Copy and paste the dlg_settings_slide_in state to duplicate it. Rename the duplicate to dlg_settings_slide_out, and set its Speed to -1.

Screen Shot 2015-11-18 at 3.28.05 PM

Note: This time, don’t change the default state! dialog’s default state should stay dlg_settings_slide_in.

Click the + button and add a new Bool parameter named isHidden.

Create two transitions between the states, just as you did for the buttons. Then add the isHidden parameter of type Bool.

Change the condition of the dlg_settings_slide_out => dlg_settings_slide_in transition to be isHidden equals false. For the dlg_settings_slide_in => dlg_settings_slide_out transition change the condition to isHidden equals true.

Screen Shot 2015-11-18 at 3.31.36 PM

Next, right click in the Animator and select Create State and then choose Empty.

Screen Shot 2015-11-18 at 8.35.29 PM (2)

In the Inspector, name the state idle. Next, right click the state and choose Set Layer as Default State. Finally, create a transition between idle to dlg_settings_slide_in. Set the Condition as isHidden is equal to false.

It should look as follows:

Screen Shot 2015-11-18 at 8.40.32 PM

Run the scene now and you’ll see the dialog sliding in at the start, and then overlapping the buttons.

36

This is getting there, but still not what you want. You need to disable the Animator component so it won’t play the animation at the start. You want the dialog to appear on demand which you’ll do next.

Displaying Dialog on Button Click

When you run the scene, the dialog doesn’t appear straight away. This is good — however, it won’t show up even when you click the settings button. This — is not good.

My friend, you’re looking at your next problem to solve.

Open the UIManagerScript in MonoDevelop and add following instance variable:

public Animator dialog;

Then add following code to the end of OpenSettings:

public void OpenSettings() {
    //..skipped..
 
    dialog.SetBool("isHidden", false);
}

This enables the Animator component and sets the correct value to the isHidden parameter.

Finally add new method called CloseSettings as follows:

public void CloseSettings() {
    startButton.SetBool("isHidden", false);
    settingsButton.SetBool("isHidden", false);
    dialog.SetBool("isHidden", true);
}

This returns the buttons and hides the dialog. You’ll add the UI element that calls this method in a moment.

Save the UIManagerScript and switch back to Unity.

Select UIManager in the Hierarchy and drag Dlg_Settings to the Dialog field in the Inspector.

38

Run the scene, then click the Settings button and see how the buttons slide out as the dialog slides in.
That’s better, but you can’t close the dialog.

To fix this, you need to add some kind of close button to the dialog.

Adding the Close Button

Select GameObject\UI\Button to create a button. Rename this new button to Btn_Close and drag it over Dlg_Settings in the Hierarchy to add it as a child object. Also, this button won’t have text on it, so remove the Text object nested in Btn_Close.

This is what you should have in the Hierarchy at this point:

39

Now select Btn_Close and follow these steps:

  1. Set Anchors to top-right.
  2. Set both Pos X and Pos Y to 0.
  3. Open the Menu folder in the Project Browser and drag settings_btn_close to the Source Image field in the Inspector.
  4. Click Set Native Size.

40

This is how the dialog should look in the Scene view now:

41

Note: This time, you’re going to use another method to highlight the button’s image (Transition property in the Button script) called ColorTint, which is the default transition type. You’ll do this instead of adding two more images to represent highlighted and pressed button states.

The button looks great, but it does nothing. Fortunately, you’ve already added the method this button needs to call.

Select Btn_Close in the Hierarchy, scroll down to the On Click() list and click +. Drag UIManager from the Hierarchy to the new item and then select the UIManagerScript\CloseSettings () method in the dropdown.

42

Run the scene. Click the Settings button and close the scene by clicking Close after the dialog slides into the scene.

43

Hey, you’ve done well. That looks nice! :]

Adding Sound Settings

There’s not much sense in keeping a meaningless settings dialog, so, it’s time to add some actual settings to it. In this dialog, the player will have control over the music’s volume in the menu scene.

Music? Yes, what fun is a game without a rockin’ soundtrack?

Adding Music to the Menu Scene

You’re welcome to rummage around your files for a suitable clip, but you don’t have to because the project already contains a snappy music track. All you need to do is to play it.

Select Main Camera in the Hierarchy and add the Audio Source component. Then, in the Project Browser, open the Audio folder and drag music to the Audio Clip field in the Inspector.

Enable Play On Awake.

44

Toggling Music On and Off

To toggle music on and off you’re going to use a…wait for it…toggle control. Select GameObect\UI\Toggle to add a toggle UI element to the scene.

45

The toggle controls consist of the root object which has a Toggle script attached, and several child objects:

  • Background: Image that is always visible (i.e. in both On and Off states)
  • Checkmark: Image that is only visible when toggle is active (ON).
  • Label: A label displayed next to toggle.

You don’t need a label this time, so remove the nested Label. Then rename toggle to Tgl_Sound and drag it over Dlg_Settings to put it inside the dialog. This is what you should see in the Hierarchy after you’re done:

46

Select Tgl_Sound in the Hierarchy. Set its Anchors to middle-left, Pos X to 115 and Pos Y to -10.

47

Note: Remember how anchors and position are set relative to the parent? This is why it’s important to add tgl_sound as a child of dlg_settings first and only after that set its position.

Keep in mind, changing anchors and pivot won’t change the UI element position, instead, they update position fields (e.g. Pos X, Pos Y, Left, Right) to values that position the element at the same place by using new anchors and pivot. Set these first, and play with the them to set the correct position.

Also, under the Toggle (Script) component, uncheck the Is On checkbox.

Now you need to specify images for the Background and Checkmark child objects. Just as you’ve done with the other images, you will take them from the Menu folder, so open that folder in the Project Browser.

You’re going to need two images:

  • settings_btn_sound for Background
  • settings_btn_sound_checkmark for Checkmark

Select Background contained in tgl_sound in the Hierarchy and drag settings_btn_sound from the Project Browser to Source Image in the Inspector. Then click Set Native Size.

48

Then select Checkmark and repeat the previous steps, but this time use the settings_btn_sound_checkmark image from the Project Browser.

49

This is what you should see in the Scene View:

50

Note: As you can see, the size of the root object (wide rectangle) doesn’t match the background images. You can adjust its size, but it is just fine this way.

Muting the Music

The good thing about UI elements’ event handlers is that sometimes you can get away without writing any code at all. Instead, you can set the UI element to change the property or directly call a function of the component attached to the object using only Unity’s interface.

Here’s how you can change the mute property of the Audio Source component attached to MainCamera.

Select Tgl_Sound in the Hierarchy, and in the Inspector find the On Value Changed (Boolean) list. Click + to add a new item.

51

Drag MainCamera from the Hierarchy to the newly added item. Open the function selection dropdown and select AudioSource\mute from the Dynamic bool section at the top.

52

Note: When you look closely at the function selection options, you’ll see two mute properties: one in the Dynamic bool section and the other in Static Parameters.

The difference is quite trivial. If you select mute in the Dynamic bool section, its value will be set to the current value of the toggle’s Active property each time you toggle it.

If you select the mute property from the Static Parameters section, the new input field will appear and you’ll be able to set its value in the Inspector to some constant value.

Of course, in the Dynamic bool section there are only properties and methods that take Bool values, because toggle’s active property type is Bool. Since you can specify any value as the static parameter, the Static Parameters section contains all public properties and methods.

Hence, when the toggle is active (e.g. active equals true) it sets the mute property of AudioSource to true and mutes the music.

Run the scene, open the settings dialog and try switching music ON and OFF.

Using Slider to Regulate the Volume

It’s really cool that toggle can synchronize its ON and OFF states with some other component’s field, but what if you have a range of values? In this case, you can use the Slider UI element.

Select GameObject\UI\Slider to add a slider. Rename it to Sdr_Volume and put it inside Dlg_Settings.

53

Select Sdr_Volume in the Hierarchy and set its Anchors to middle-right. Then set its Pivot to (1, 0.5) so that you could position it using the middle point of its right edge.

Finally set its Pos X to -20, Pos Y to -10, Width to 270 and Height to 35.

54

This is how the Settings dialog should look right now:

Screen Shot 2015-11-18 at 9.36.13 PM

If you take a look at the Hierarchy, you’ll see the slider control has more parts than a toggle or button. Here are the main parts:

  • Background: Image that shows the bounds of the slider and its inner area when it’s not filled (i.e. when handle is all the way to the left).
  • Handle: Image for the handle. You drag it to change the slider’s value.
  • Fill: Image that stretches to show the value of the slider.

In fact, the fill image is not the only part that can stretch, so normally it’s better to use 9-scale images for all three parts. And you have such images! Lucky you! :]

Open the Menu folder in the Project Browser and find three images corresponding to each part of the slider: slider_background, slider_fill and slider_handle.

56

For each image, open the Sprite Editor in the Inspector and set all values for Border to 8. Click Apply.

57

Now you need to set the corresponding image for each part of the slider:

  1. Select Background and drag slider_background to Source Image in the Inspector.
  2. Select Fill (not Fill Area) and drag slider_fill to Source Image.
  3. Select Handle and drag slider_handle to Source image.

If you run the scene now and open the Settings dialog, you should see something like this:

58

Changing the Volume of the AudioSource Component

Changing the music volume using the slider is similar to what you did with the toggle.

Select Sdr_Volume in the Hierarchy. In the Inspector, scroll down to see the On Value Changed (Single) list and click + to add a new item.

Drag MainCamera from the Hierarchy to that new item in the list, open the function selection dropdown and select AudioSource\volume in the Dynamic float section.

59

Run the scene, open the Settings dialog and change the slider’s value. You should hear the volume go up and down as you drag the slider handle. Personally, I find it to be a super-awesome feature. :]

Where To Go From Here?

Just as I promised in the end of Part 1, in this part you’ve added more controls, learned how to animate them and made a fully functioning menu scene. While it’s fairly simple, you’ve explored most of the UI controls.

If you’d like to see it in its final, perfect form, download it here: Rocket Mouse Part Two Final Project.

In Part 3, the final part, you’re going to learn advanced techniques, including using the mask component to create a sliding menu. Also, you’ll create more animations and learn how to migrate legacy GUI code to the Unity UI.

If you have any questions, comments or discoveries to share, please feel free to join the conversation below.

The post Introduction to Unity UI – Part 2 appeared first on Ray Wenderlich.

Introduction to Unity UI – Part 3

$
0
0
Note: This tutorial is part of the Unity Feast. To see more tutorials being featured in the Unity Feast as well as to learn how to take part in the Unity Feast game jam, click over here.

Update 11/20/15: This tutorial was updated to Unity 5.2 by Pedro Pereira & Orlando Pereira. Original post by tutorial team member Kirill Muzykov.

Creating sliding menus in Unity is now a snap!

Creating sliding menus in Unity is now a snap!

The third and final part of this series all about Unity’s UI.

In Part 1, you created a menu scene, complete with an adaptive background and neatly controlled graphical elements, thanks to expert-level use of anchors, pivot and other cool tricks.

Part 2 was all about animating buttons and actions to make your game uber-interactive.

Now you’re going to build on these skills to round out your understanding of Unity’s UI, but you’re not going to stop with a fancy new menu. You’ll also migrate the RocketMouse game scene from the old legacy GUI system to the new UI system.

Getting Started

To start, simply open the Unity project at the point where you left it at the end of Part 2.

If you tinkered with your old project file to a point beyond recognition — or skipped the last part — you can download the final project for Part 2 here: RocketMouse_UI_Part2_Final. Unpack it and open it in Unity.

Strap yourself in, this tutorial is about to get real.
01

Creating a Sliding Menu

In many cases, you want to provide your users easy access to some game options or features, but don’t want to waste space on the screen. This is a job for a sliding menu.

You’ve seen these before: they’re a control that comprises a small, unassuming button that is always visible and a menu that slides out to reveal options. Your first step is adding that button.

Adding an Open Button

You should already know how to add a button after working through the first two parts of this series, but if not, the following directions should be ample for you to accomplish the task.

Select GameObject\UI\Button in the menu. Rename the newly added button to Btn_Slide and remove the nested Text object, since the button won’t need a label.

Select Btn_Slide in the Hierarchy and open the Menu folder in the Project Browser. Drag the btn_9slice_normal image to the Source Image field in the Inspector.

Now set the button position and size as follows:

  1. Set Anchors to bottom-left.
  2. Set both Pos X and Pos Y to 80.
  3. Set Width and Height to 64.

02

And that’s how simple it is to complete the first step.

Add the Masking Panel

To create this control, you’re going to need two panels. One will define the mask and the other will move within the mask.

Note: If you’re not entirely sure what a mask is, don’t sweat it. Just follow the steps and you’ll see how it works in real-time. You’ll need to have both panels to see it in action.

Select GameObject\UI\Panel to create the first panel that will be the mask. This will add a Panel to the Hierarchy. Select it and follow these steps:

  1. Rename it to Pnl_Mask.
  2. Drag it over Btn_Slide to add it as a child object.
  3. Set Anchors to top-center.
  4. Set Pivot to (0.5, 0)
  5. Set both Pos X and Pos Y to 0.
  6. Set Width to 64 and Height to 192.
  7. Add the mask component by clicking Add Component button and selecting UI\Mask.
  8. Uncheck Show Mask Graphic inside the mask component dialog.

03

Note: You don’t always have to add the panel with a mask as a child node of the button. But when you do, you ensure that when the button moves, the masking panel moves with it.

Adding the Content Panel

Add another panel by selecting GameObject\UI\Panel and following these steps:

  1. Rename it to Pnl_Content
  2. Add it as a child of Pnl_Mask

    Note: Did you notice that you can see only a small portion of the white panel, although its size didn’t change? After adding it as a child of the panel with a mask, you now only see the portion of pnl_content that is inside the rect of pnl_mask.

  3. Set the Anchors to stretch-stretch.
  4. Set Left, Top, Right and Bottom to 0.
  5. Set Pivot to (0.5, 1)

04

Now it’s time to change the background image for the content panel.

Open the Menu folder in the Project Browser and select the slide_menu_panel_9slice image. Open Sprite Editor in the Inspector and set all Border values to 8. Click Apply!

05

After that, select Pnl_Content in the Hierarchy, and then drag slide_menu_panel_9slice from the Project Browser to the Source Image field in the Inspector.

On the following GIF, you can see both how the content panel should look and how the mask component works. Now you see it, now you don’t

06

Note: As you can see, a mask works similarly to a window in a wall. If someone is walking along a wall, you can only see him when he passes by a window. Another way to think of it is as a cloaking device that allows only a portion of the image to show through.

Adding Buttons

You’re about to add three buttons to the sliding menu.

To create the first button, select GameObject\UI\Button. Rename it to Btn_About and remove the text child.

Drag the Btn_About button onto Pnl_Content in the Hierarchy to add it as a child. Open the Menu folder in the Project Browser and drag slide_menu_btn_about to the Source Image in the Inspector. Click Set Native Size.

Set Anchors to top-center and Pivot to (0.5, 1). After that, set both Pos X to 0 and Pos Y to 0.

Now it’s your turn to add two remaining buttons, all by yourself.

Name them Btn_Achievements and Btn_Leaderboards and use the slide_menu_btn_achievements and the slide_menu_btn_leaderboards images respectively.

If you need a nudge, feel free to open up the spoiler.

Solution Inside: Adding More Buttons SelectShow>

This is what you see in the end:

07

Making the Panel Slide Up and Down

To make the panel slide up and down, you’re going to use the same technique you’ve already employed for buttons and the settings dialog.

It will be easy, just follow these steps:

  1. Select Pnl_Content in the Hierarchy and open the Animation view.
  2. Create a new clip by clicking on the Create button.
  3. Name the animation sliding_menu_down and save it the Animations folder.

    09

  4. Click on the 1:00 mark in the timeline. This should also enable recording in the Animation view. Turn it on by pressing the red circle button, and then look for the playback controls to turn red.

    10

  5. Set the Top to 192 in the Inspector and then stop recording.

    11

  6. Open the Animations folder in Project Browser and select sliding_menu_down. Uncheck Loop Time in the Inspector.

    12

  7. Select Pnl_Content in Hierarchy and open the Animator view. Copy and paste the sliding_menu_down state to create a duplicate.

    Screen Shot 2015-11-18 at 10.24.05 PM

  8. Rename the duplicate to sliding_menu_up and set its Speed to -1 in the Inspector.
  9. Screen Shot 2015-11-18 at 10.29.29 PM

  10. Create two transitions: from sliding_menu_up to sliding_menu_down and from sliding_menu_down to sliding_menu_up.

    Screen Shot 2015-11-19 at 12.09.55 AM

  11. Add a new Bool parameter named isHidden and set its default value to true.

    Screen Shot 2015-11-18 at 10.34.43 PM

  12. Select the transition from sliding_menu_up to sliding_menu_down, and in the list of conditions set isHidden to true.
  13. Screen Shot 2015-11-19 at 12.12.54 AM

  14. Select the transition from sliding_menu_down to sliding_menu_up, and this time set Conditions to be isHidden equals false.

    Screen Shot 2015-11-19 at 12.14.36 AM

  15. Next, right click in the Animator and select Create State and then choose Empty.
    Screen Shot 2015-11-19 at 12.16.10 AM (2)
  16. In the Inspector, name the state idle. Next, right click the state and choose Set Layer as Default State. Create a transition between idle to sliding_menu_up. Set the Condition as isHidden is equal to false.
    Screen Shot 2015-11-19 at 12.18.28 AM
  17. Select Pnl_Content in the Hierarchy and open the Animation View. Create a new animation clip and call it idle.Screen Shot 2015-11-18 at 11.30.53 PM (2)
  18. In the first keyframe, set the Top to be 192.
    Screen Shot 2015-11-18 at 11.41.54 PM

That’s it, 17 easy steps! :] Unfortunately, when you run your game, nothing happen.

Adding Code to Toggle the Menu

Now it’s time to make things move and you’ll do this in code. Open the UIManagerScript in MonoDevelop and add following instance variable:

public Animator contentPanel;

After that, add the following method:

public void ToggleMenu() {
    bool isHidden = contentPanel.GetBool("isHidden");
    contentPanel.SetBool("isHidden", !isHidden);
}

This enables the animator component when you open the sliding menu and sets the correct isHidden parameter value.

Save the script and switch back to Unity. In Unity, select UIManager in the Hierarchy and drag Pnl_Content from the Hierarchy to the Content Panel field in the Inspector.

20

Now, select Btn_Slide in the Hierarchy. In the Inspector, find a list of On Click (Button) event handlers and add a new one by clicking the + button.

After that, drag UIManager from the Hierarchy to that new handler. Then, in the function selection dropdown, select UIManagerScript\ToggleMenu ().

21

Run the scene and relish in your cool sliding-up-and-down menu.

Adding a Rotating Gear Icon

There is something missing, don’t you think? Oh, of course! The rotating gears icon on the opening button itself — the one shown in the animated GIF image at the start of this part.

Adding the Gear Image

Your first step is to add an image as a child object of btn_slide, and animate it during the menu opening and closing animations.

Choose GameObject\UI\Image to create a new image. Drag it over Btn_Slide in the Hierarchy to add it as a child object.

After that, follow these steps:

  1. Rename the image to Img_Gear
  2. Set the Anchors to middle-center
  3. Set both Pos X and Pos Y to 0.
  4. Open the Menu folder in Project Browser and drag the slide_menu_gear image to the Source Image field in the Inspector.
  5. Click Set Native Size.

22

Animating the Gear Image

By now, the technique of creating two animation states and a parameter to switch between them should be second nature. So, you should be able to create a left-rotating gear and reverse the animation to make a right-rotating gear on your own.

Here are the need-to-know details:

  • Animation duration should be identical to the sliding panel animation, and this is easy since all animations in this tutorial are exactly 1 second long.
  • The gear should rotate 360 degrees around the Z axis (Rotation Z).
  • Use the same name isHidden for parameter name and set its default value to true.
  • Remember to disable looping and the Animator component.

Should you find that you need more detailed directions, feel free to open the spoiler below.

Solution Inside: Rotating the Gear SelectShow>

Triggering the Gear Animation from Code

To complete the sliding menu control, you need to trigger the gear animation from code, but you only need to write a few lines.

Open the UIManagerScript in MonoDevelop and add following instance variable:

public Animator gearImage;

Then scroll down and find the ToggleMenu method. Add the following to the bottom of the method’s body:

public void ToggleMenu() {
    //..skipped..
 
    gearImage.SetBool("isHidden", !isHidden);
}

This enables the Animator component and sets its isHidden parameter to the same value as the content panel’s Animator isHidden parameter.

Save the script file and switch back to Unity.

In Unity, select UIManager in the Hierarchy. Drag Img_Gear to the Gear Image field in the Inspector.

23

Run the scene and enjoy your fancy rotating gear icon.

24

Good job! The sliding menu is complete and your scene is coming together.

You’re not going to handle clicks on the buttons in the menu, because you should be already familiar with handling UI events and actually integrating Game Center would send this tutorial down a rabbit hole. Instead, you’re going to update the old GUI-based RocketMouse scene so that it uses the new GUI system.

Updating the RocketMouse Scene to use Unity’s UI

In the RocketMouse game, a few UI elements use the old GUI method to display: the points scored and the button to restart the game. You’re going to replace them with new text and image UI elements, and a dialog that allows you to restart the game or exit to the main menu.

Adding the Points Label

Switch to the RocketMouse scene and open the Scenes folder in the Project Browser. Double-click on the RocketMouse scene to open it.

Choose GameObject\UI\Text to create a new Text UI element. You’re also going to work with Canvas and EventSystem while you’re in here.

25

Select Text in the Hierarchy and make following changes in the Inspector:

  1. Rename it to Txt_Points.
  2. Set Anchors to top-left.
  3. Set Pivot to (0, 0.5).
  4. Set Pos X to 50 and Pos Y to -30.
  5. Change Text to 0, since the player starts with zero points.
  6. Open the Fonts folder in the Project Browser and drag TitanOne-Regular to the Font field in the Inspector.
  7. Set Font Size to 24.
  8. Set Horizontal Overflow to Overflow to make sure the label can display even the most outrageous scores.

26

Also, don’t forget to change the color of the text to be white.

Adding a Points Icon

Nowadays, simply displaying text to show the points is not enough. You need to make sure that it’s perfectly clear what this text means from the moment the player’s eyes see it.

Yes, players these days are spoiled by impressive UI on even the simplest apps, so you need to add an icon to make the score perfectly crisp, clear and well-defined.

Select GameObject\UI\Image to create a new Image. Select it in the Hierarchy and follow these steps:

  1. Rename it to Img_Points
  2. Drag it over Txt_Points to add it as a child, so that when you move the label the icon moves, too.
  3. Set Anchors to middle-left.
  4. Set Pivot to (1, 0.5).
  5. Set both Width and Height to 32.
  6. Set Pos X to -5 and Pos Y to 0.
  7. Open the Sprites folder in the Project Browser and drag the coin image to the Source Image field in the Inspector.

Note: This time you do not click Set Native Size, because you’re going to reuse the image for coins in the game, which will be a bit bigger than the icon.

Updating the Points Label

Most of the code of the game lives in the MouseController.cs script, so you’ll edit this script to update the points label. In fact, until the end of this tutorial, you’ll only work with this script.

Note: Normally, I’d break this huge script into several smaller chunks, but I don’t want you to waste your time on housekeeping, especially because refactoring will take more time and will require a strong understanding of existing code.

It’s better to work with it in a big ol’ block so you can just make the small changes needed and move on with your life.

Open the Scripts folder in the Project Browser and double-click on the MouseController script to open it in MonoDevelop.

When the script loads, find and remove following methods, which use the old GUI system:

  • onGUI
  • DisplayCoinsCount
  • DisplayRestartButton

Add the following using directive:

using UnityEngine.UI;

After that, add the following instance variable to contain a reference to the label:

public Text coinsLabel;

Finally, add the following line at the end of CollectCoin, which is called every time the mouse collects a coin.

coinsLabel.text = coins.ToString();

Save the script file and switch back to Unity.

In Unity, select mouse in the Hierarchy and drag Txt_Points to the Coins Label field in the Inspector.

27

Run the scene and send the mouse out to collect a few coins. You should see the label update when he collects a coin.

28

Everything is looking good, but you might have noticed one rather embarrassing problem. When you removed the old onGUI method you also removed the button that displayed when the mouse dies, leaving the player unable to restart the game. Doh!

Adding a Restart Dialog

I think you’ve got a good handle on the new GUI system and can create this dialog without a bunch of prodding from me. So create a panel with a label and two buttons that looks like this:

29

Place it in the center of the canvas.

30

Come back when you’re done – you’re on your own, friend!

Gotcha? :] Of course I’m not going to leave you hanging. If you’d like a step-by-step, just open up the spoiler below.

Solution Inside: Solution SelectShow>

Displaying the Restart Dialog

You’re not going to animate the appearance of the dialog. Instead, you’ll just hide the dialog at the start and show it when the player loses the game.

Open the MouseController script in MonoDevelop and add the following instance variable:

public GameObject restartDialog;

Then add following line of code in the Startmethod to hide the dialog at the start:

restartDialog.SetActive(false);

Scroll down and add following line to the end of the HitByLaser method:

restartDialog.SetActive(true);

As you probably guessed, the HitByLaser method is called when the mouse dies. Hence, it’s the perfect place to display a restart dialog.

Add the following two methods to restart and exit the game:

public void RestartGame() {
    Application.LoadLevel (Application.loadedLevelName);
}
 
public void ExitToMenu() {
    Application.LoadLevel ("MenuScene");
}

You’ll link them to the corresponding buttons in a moment.

Save the script file and switch back to Unity.

In Unity, select Mouse in the Hierarchy and drag Dlg_Restart to the Restart Dialog field in the Inspector.

36

Then select Btn_Restart in the Hierarchy and scroll down to the On Click (Button) list.

Click + to add a new item. After that, drag Mouse from the Hierarchy to the new item. In the function selection dropdown, select MouseController\RestartGame ().

37

Now, select Btn_Exit, and repeat the process, but this time select the MouseController\ExitToMenu () function.

Run the scene and send your mouse into the laser’s line of fire. You should see a dialog appear instantly after he dies. If you press Restart, you’ll restart the game. If you press Exit you’ll return to the main menu.

38

And once again I’m ending a tutorial on a high note — with an image of the poor, lifeless mouse. Sorry, no kittens today, maybe in the next series. :]

Where To Go From Here?

Congratulations on completing this tutorial! You can download the final project here: RocketMouse Final.

I hope you like the UI system and are excited to create some cool user interfaces in your games! Surely, the prospect of minimal coding alone should have you feeling a bit gleeful.

If you create some awesome control using the UI system, we’d all love to see your handiwork. Go ahead and post a screenshot, video or GIF animation in comments to show the world your awesome new skills — and maybe inspire a fellow dev or few (or make them jealous). :]

If you have any questions or comments, please leave them below. I will be happy to answer!

Good luck!

The post Introduction to Unity UI – Part 3 appeared first on Ray Wenderlich.

Join the Unity Feast Game Jam!

$
0
0
Introducing the Unity Feast!

Let’s Jam with a Game Jam!

During this week’s Unity Feast, we have released a full menu of free Unity tutorials:

  1. First Course: Introduction to Unity
  2. Second Course: Introduction to Unity 2D
  3. Third Course: Introduction to Unity Animation
  4. Fourth Course: Make a VR Game With Unity and Google Cardboard
  5. Fifth Course: Introduction to Unity Particle Systems
  6. Sixth Course: Introduction to Unity UI System

After such a delicious meal, it’s now time to dig into dessert. That is, our Unity Game Jam!

This is an invitation for you to join our Unity Feast Game Jam. This is a great way to learn Unity, have fun, and have a chance to win some great prizes – such as a new Apple TV!

Keep reading to find out how to enter, the game jam theme, and to see the full list of prizes.

What is the Unity Feast Game Jam?

The Unity Feast Game Jam is a challenge for you to make a game in Unity, using a theme we provide.

We are running this game jam because we wanted to give you a chance to practice some of the skills you learned from our new Unity tutorials that came out this week. Tutorials are a great way to learn, but making your own game is even better!

Your challenge in the Unity Feast Game Jam is to make either a 2D or 3D Unity game around the theme of eating. To make things interesting, we are providing five different objects. You must include at least two of these objects in your game:

unity_gamejam_art

Note: Here is a 2D art pack of these items, courtesy of Vicki from Game Art Guppy.

You don’t have to use this exact art (for example, you could make your own 3D cat if you wanted) – the important part is that the game is about eating and at least 2 of these objects are represented in some way in your game.

The game jam is open to all, but the game jam is only eligible for single entries. Yes, you can work as a team, but you will have to submit as one team and if you win, you will only receive one prize.

All members of the raywenderlich.com team are eligible to enter, with exception to the raywenderlich.com Unity Team. The raywenderlich.com Unity Team will be the judges for the contest, to see who wins the cool prizes listed below!

Prizes

Not only will you learn a ton and have fun by entering the Unity Feast Game Jam, but you’ll have a chance to win some amazing prizes!

Grand Prize Winner

The grand prize winner will win the latest and greatest Apple TV to play your Unity games. The winner will also receive a $50 Steam gift card that you can use to get some great games made with Unity. Total value: $250

Runners Up Prizes

  1. One winner will receive a license to UFPS : Ultimate FPS. This a Unity framework for creating AAA quality first person shooter games in Unity. Total value: $95
  2. One winner will receive a license to Shader Forge. Shader Forge is visual tool integrated into Unity for creating new shaders for your game. No longer do you have to muddle over cryptic shader languages when you can design your shaders using this incredibly user friendly tool. Total value: $90
  3. One winner will receive a license to Texture Packer and Sprite Illuminator. While Unity includes it’s own texture packer, this third party tool creates really efficient sprite sheets for your games. Sprite Illuminator also also you to provide normal maps to your 2D artwork. Total value: $60
  4. One winner will receive a license to 2D Homing Missiles, 2D Laser Pack, and 2D Shooter Bullet and Weapon System. Looking to take your 2D shooter to the next level? These plugins will add some awesome visual juice to your game that will make it stand out. These plugins were developed by raywenderlich.com Unity Team member, Sean Duffy. Total value: $40

In total, this is over $500 in prizes – just for learning Unity and having fun! :D

Unity Feast Game Jam Details

The game jam begins now and ends this Sunday at 11:59 PM EST – so feel free to start your game whenever you’re ready!

  • Start Time: Now
  • End Time: Sunday November 22 @ 11:59 PM EST
  • What to Submit: A game made in Unity with the theme eating. Must include at least 2 of the following objects: food, helicopter, cat, bugs, and boxing gloves.
  • Where to Submit: Email a zip file of your entire Unity project to brian@razeware.com by Sunday November 22 @ 11:59 PM EST.
Note: You should save your entire Unity project in a zip file. Send the entire Unity project, not the game built for a particular platform.

If you do not send your entire project by Sunday November 22 @ 11:59 PM EST, or if your project does not run without any modifications the game will be considered a void entry and WILL NOT be judged.

Once we receive your entry, we will immediately download it then distribute it to the team to judge. Winners will be announced on Friday, November 27th.

Where To Go From Here?

So set forth and make your Unity game – and be sure to check out our new Unity tutorials if you need a little help!

Beyond that, if you’re looking inspiration, support, or a little tough love during this game jam, we’ve set up a Slack channel just for game jam participants.

Slack is a free messaging client. If you wish to join the Slack channel, head over here to sign up!

Note: The channel will only be live during the duration of the game jam.

With that said, start making those games. On behalf of the raywenderlich.com Unity Team, I can’t wait to see what you come up with. Have fun! :]

The post Join the Unity Feast Game Jam! appeared first on Ray Wenderlich.

Viewing all 4369 articles
Browse latest View live


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