Как сделать npc unity

NPC Follow Player in Unity

Non-Player Characters or NPCs are the characters that are not controlled by a human player and instead are controlled by the scripts or the AI.

The most common task that NPCs have to do, is to follow or chase the Player.

In this tutorial, I will be showing how to make an NPC that follows the player in Unity.

Step 1: Create a Player Controller

We will create a simple Player Controller, so we can walk around and test the NPC:

  • Create new GameObject (GameObject -> Create Empty) and name it “Player”
  • Create new Capsule (GameObject -> 3D Object -> Capsule), move it inside Player Object and change its position to (0, 1, 0)
  • Remove the Capsule Collider component from a Capsule
  • Move the Main Camera inside Player Object and change its position to (0, 1.64, 0)

Create a new script, name it SC_CharacterController then paste the code below inside it:

SC_CharacterController.cs

  • Attach the SC_CharacterController script to Player Object and assign a child Main Camera to a Player Camera variable
  • You will notice it automatically added another component called Character Controller, change its center position to (0, 1, 0)

Step 2: Create the NPC

To create an NPC, follow the steps below:

  • Create a new GameObject and name it “NPC”
  • Create a new Capsule, move it inside NPC Object and change its position to (0, 1, 0)
  • Create new Material and name it “npc_material”
  • Change the color of npc_material to red
  • Assign npc_material to Capsule inside NPC Object (this is just so we can distinguish NPC from the Player)

Before continuing, we need to bake the NavMesh in our Scene.

NavMesh stands for «Navigation Mesh» and is used in pathfinding to allow NPCs to navigate the level without bumping into the obstacles.

To bake the NavMesh, follow the steps below:

  • Mark every static Object in the Scene as Navigation Static

  • Go to Navigation Window (Window -> AI -> Navigation), select Bake Tab then click Bake

After the NavMesh is baked, it should look something like this:

Now we can move to the programming of the NPC movement:

  • Attach NavMesh Agent component to NPC Object
  • Create a new script and name it SC_NPCFollow
  • Attach SC_NPCFollow script to NPC Object
  • Open the SC_NPCFollow script

First, we begin by adding a UnityEngine.AI namespace at the beginning of the script:

Then we define the necessary variables:

In the void Start() we begin by getting the NavMesh Agent component attached to this Object:

And finally, in the void Update() we instruct the NavMesh Agent to follow the Player:

Here is the final SC_NPCFollow.cs script:

Fixing some issues:

Issue 1: After pressing Play, the NPC capsule hovers above the ground:

Solution: Change the Base Offset variable in NavMesh Agent to a negative value (in my case it’s -0.08)

Issue 2: The NPC comes too close when following the Player:

Solution: Change Stopping Distance in NavMesh Agent to a higher value (in my case I set it to 5)

The NPC is now ready, let’s test it:

Everything works as expected, the NPC now follows the Player and stops at a set distance.

Источник

How to create non-player Characters (NPC) with Unity 2018

Today, we will learn to create game characters while focusing mainly on non-player characters. Our Cucumber Beetles will serve as our game’s non-player characters and will be the Cucumber Man’s enemies. We will incorporate Cucumber Beetles in our game through direct placement. We will review the beetles’ 11 animations and make changes to the non-player character’s animation controller. In addition, we will write scripts to control the non-player characters. We will also add cucumber patches, cucumbers, and cherries to our game world.

Читайте также:  Террария как сделать эссенцию

Understanding the non-player characters

Non-player characters commonly referred to as NPCs, are simply game characters that are not controlled by a human player. These characters are controlled through scripts, and their behaviors are usually responsive to in-game conditions.

Our game’s non-player characters are the Cucumber Beetles. These beetles, as depicted in the following screenshot, have six legs that they can walk on; under special circumstances, they can also walk on their hind legs:

Cucumber Beetles are real insects and are a threat to cucumbers. They cannot really walk on their hind legs, but they can in our game.

Importing the non-player characters into our game

You are now ready to import the asset package for our game’s non-player character, the Cucumber Beetle. Go through the following steps to import the package:

  1. Download the Cucumber_Beetle.unitypackage file from the publisher’s companion website
  2. In Unity, with your game project open, select Assets | Import Package | Custom Package from the top menu
  3. Navigate to the location of the asset package you downloaded in step 1 and click the Open button
  4. When presented with the Import Asset Package dialog window, click the Import button

As you will notice, the Cucumber_Beetle asset package contains several assets related to the Cucumber Beetles, including a controller, scripts, a prefab, animations, and other assets:

Now that the Cucumber_Beetle asset package has been imported into our game project, we should save our project. Use the File | Save Project menu option.

Next, let’s review what was imported.

In the Project panel, under Assets | Prefabs , you will see a new Beetle.Prefab . Also in the Project panel, under Assets , you will see a Beetle folder. It is important that you understand what each component in the folder is for. Please refer to the following screenshot for an overview of the assets that you will be using in this chapter in regards to the Cucumber Beetle:

The other assets in the previous screenshot that were not called out include a readme.txt file, the texture and materials for the Cucumber Beetle, and the source files. We will review the Cucumber Beetle’s animations in the next section.

Animating our non-player characters

Several Cucumber Beetle animations have been prepared for use in our game. Here is a list of the animation names as they appear in our project, along with brief descriptions of how we will incorporate the animation into our game. The animations are listed in alphabetical order by name:

Animation Name Usage Details
Attack_Ground The beetle attacks the Cucumber Man’s feet from the ground
Attack_Standing The beetle attacks the Cucumber Man from a standing position
Die_Ground The beetle dies from the starting position of on the ground
Die_Standing The beetle dies from the starting position of standing on its hind legs
Eat_Ground The beetle eats cucumbers while on the ground
Idle_Ground The beetle is not eating, walking, fighting, or standing
Idle_Standing The beetle is standing, but not walking, running, or attacking
Run_Standing The beetle runs on its hind legs
Stand The beetle goes from an on-the-ground position to standing (it stands up)
Walk_Ground The beetle walks using its six legs
Walk_Standing The beetle walks on its hind legs

You can preview these animations by clicking on an animation file, such as Eat_Ground.fbx , in the Project panel. Then, in the Inspector panel, click the play button to watch the animation.

Читайте также:  Как сделать частные деньги

There are 11 animations for our Cucumber Beetle, and we will use scripting, later to determine when an animation is played.

In the next section, we will add the Cucumber Beetle to our game.

Incorporating the non-player characters into our game

First, let’s simply drag the Beetle.Prefab from the Assets / Prefab folder in the Project panel to our game in Scene view. Place the beetle somewhere in front of the Cucumber Man so that the beetle can be seen as soon as you put the game into game mode.

A suggested placement is illustrated in the following screenshot:

When you put the game into game mode, you will notice that the beetle cycles through its animations. If you double-click the Beetle.controller in the Assets | Beetle folder in the Project panel, you will see, as shown in the following screenshot, that we currently have several animations set to play successively and repeatedly:

This initial setup is intended to give you a first, quick way of previewing the various animations. In the next section, we will modify the animation controller.

Working with the Animation Controller

We will use an Animation Controller to organize our NPCs’ animations. The Animation Controller will also be used to manage the transitions between animations.

Before we start making changes to our Animation Controller, we need to identify what states our beetle has and then determine what transitions each state can have in relation to other states.

Here are the states that the beetle can have, each tied to an animation:

  • Idle on Ground
  • Walking on Ground
  • Eating on Ground
  • Attacking on Ground
  • Die on Ground
  • Stand
  • Standing Idle
  • Standing Walk
  • Standing Run
  • Standing Attack
  • Die Standing

With the preceding list of states, we can assign the following transitions:

  • From Idle on Ground to:
    • Walking on Ground
    • Running on Ground
    • Eating on Ground
    • Attacking on Ground
    • Stand
  • From Stand to:
    • Standing Idle
    • Standing Walk
    • Standing Run
    • Standing Attack

Reviewing the transitions from Idle on Ground to Stand demonstrates the type of state-to-state transition decisions you need to make for your game.

Let’s turn our attention back to the Animation Controller window. You will notice that there are two tabs in the left panel of that window: Layers and Parameters . The Layers tab shows a Base Layer . While we can create additional layers, we do not need to do this for our game. The Parameters tab is empty, and that is fine. We will make our changes using the Layout area of the Animation Controller window. That is the area with the grid background.

Let’s start by making the following changes. For all 11 New State buttons, do the following:

  1. Left-click the state button
  2. Look in the Inspector panel to determine which animation is associated with the state button
  3. Rename the state name in the Inspector panel to reflect the animation.
  4. Click the return button
  5. Double-check the state button to ensure your change was made

When you have completed the preceding five steps for all 11 states, your Animation Controller window should match the following screenshot:

If you were to put the game into game mode, you would see that nothing has changed. We only changed the state names so they made more sense to us. So, we have some more work to do with the Animation Controller .

Currently, the Attacking on Ground state is the default. That is not what we want. It makes more sense to have the Idle on Ground state to be our default. To make that change, right-click the Idle on Ground state and select Set as Layer Default State :

Next, we need to make a series of changes to the state transitions. There are a lot of states and there will be a lot of transitions. In order to make things easier, we will start by deleting all the default transitions. To accomplish this, left-click each white line with an arrow and press your keyboard’s Delete key. Do not delete the orange line that goes from Entry to Idle on Ground.

Читайте также:  Как сделать вещь двигается

After all transitions have been deleted, you can drag your states around so you have more working room. You might temporarily reorganize them in a manner similar to what is shown in the following screenshot:

Our next task is to create all of our state transitions. Follow these steps for each state transition you want to add:

  1. Right-click the originating state.
  2. Select Create Transition .
  3. Click on the destination state.

Once you have made all your transitions, you can reorganize your states to declutter the Animation Controller’s layout area. A suggested final organization is provided in the following screenshot:

As you can see in our final arrangement, we have 11 states and over two dozen transitions. You will also note that the Die on Ground and Die Standing states do not have any transitions. In order for us to use these animations in our game, they must be placed into an Animation Controller .

Let’s run a quick experiment:

  1. Select the Beetle character in the Hierarchy panel.
  2. In the Inspector panel, click the Add Component button.
  3. Select Physics | Box Collider .
  4. Click the Edit Collider button.
  5. Modify the size and position of the box collider so that it encases the entire beetle body.
  6. Click the Edit Collider button again to get out of edit mode.

Your box collider should look similar to what is depicted in the following screenshot:

Next, let’s create a script that invokes the Die on Ground animation when the Cucumber Man character collides with the beetle. This will simulate the Cucumber Man stepping on the beetle. Follow these steps:

  1. Select the Beetle character in the Hierarchy panel.
  2. In the Inspector panel, click the Add Component button.
  3. Select New Script .
  4. Name the script BeetleNPC .
  5. Click the Create and Add button.
  6. In the project view, select Favorites | All Scripts | BeetleNPC .
  7. Double-click the BeetleNPC script file.
  8. Edit the script so that it matches the following code block:

This code detects a collision between the Cucumber Man and the beetle. If a collision is detected, the Die on Ground animation is played. As you can see in the following screenshot, the Cucumber Man defeated the Cucumber Beetle:

This short test demonstrated two important things that will help us further develop this game:

  • Earlier in this section, you renamed all the states in the Animation Controller window. The names you gave the states are the ones you will reference in code.
  • Since the animation we used did not have any transitions to other states, the Cucumber Beetle will remain in the final position of the animation unless we script it otherwise. So, if we had 100 beetles and defeated them all, all 100 would remain on their backs in the game world.

This was a simple and successful scripting test for our Cucumber Beetle. We will need to write several more scripts to manage the beetles in our game. First, there are some game world modifications we will make.

To summarize, we discussed how to create interesting character animations and bring them to life using the Unity 2018 platform.

You read an extract from the book Getting Started with Unity 2018 written by Dr. Edward Lavieri. This book gives you a practical understanding of how to get started with Unity 2018.

Источник

Поделиться с друзьями
Ответ и точка