• entries
44
19
• views
2496

# 100 Day of VR: Day 13 Attacking Enemies, Health System, and Death Animation in Unity

498 views

Welcome back to day 13 of the 100 days of VR! Last time we created enemy motions that used the Nav Mesh Agent to help us move our enemy Knight.

We added a trigger collider to help start the attack animations when the enemy got close to the player.

Finally, we added a mesh collider to the body of the knight so when it touches the player during its attack animation we’ll be able to use the damage logic.

Today we’re going to go on and implement the shooting logic for our player and to fix the annoying bug where the player would be perpetually moving after they come in contact with any other colliders.

### Fixing the Drifting Problem

My first guess at what the problem is that something must be wrong with our Rigid Body component of the player.

If we recall, the Rigid Body is in charge Unity’s physics engine on our player.

According to the documentation for RigidBody, the moment that anything collides with our player, the physics engine will exert velocity on us.

At this point we have 2 options:

• Set our velocity to be 0 after any collision
• Make our drag value higher

What is drag? I didn’t really understand it the first time we encountered it either, but after doing more research, specifically reading it here in Rigidbody2D.drag drag is how long it takes for an object to slow down over friction. Specifically, the higher the faster it is for us the faster for us to slow down.

I switched the drag value in the RigidBody from 0 to 5.

I’m not sure what the value represents, but before our velocity never decreased from friction because of our drag value, but after we added one in, we’ll start slowing down over time.

### Adding the Enemy Shooting Back into the Game

After solving the drag problem, we’re finally going back to the main portion of the game: shooting our enemy.

There will be 2 places that we’re going to have to add our code in: EnemyHealth and EnemyMovement.

EnemyHealth:

using UnityEngine;
public class EnemyHealth : MonoBehaviour
{
public float Health = 10;
    private Animator _animator;
    void Start()
{
_animator = GetComponent<Animator>();
}

public void TakeDamage(float damage)
{
if (Health <= 0)
{
return;
}
        Health -= damage;
if (Health <= 0)
{
Death();
}
}
    private void Death()
{
_animator.SetTrigger("Death");
}
}

Here’s the new flow of the code we added:

1. In Start() we instantiate our Animator that we’ll use later to play the death animation
2. In TakeDamage() (which is called from the PlayerShootingController) when the enemy dies, we call Death().
3. In Death(), we set death trigger to make the Knight play the death animation

Next, we need to make a quick change to EnemyMovement to stop our Knight from moving when it dies.

using UnityEngine;
using UnityEngine.AI;
public class EnemyMovement : MonoBehaviour
{
private NavMeshAgent _nav;
private Transform _player;
private EnemyHealth _enemyHealth;
    void Start ()
{
_nav = GetComponent<NavMeshAgent>();
_player = GameObject.FindGameObjectWithTag("Player").transform;
_enemyHealth = GetComponent<EnemyHealth>();
}

void Update ()
{
if (_enemyHealth.Health > 0)
{
_nav.SetDestination(_player.position);
}
else
{
_nav.enabled = false;
}
}
}

Here’s the code flow:

1. In Start() we grab the EnemyHealth script so we can access the knights health.
2. In Update() if the knight is dead, we disable the Nav Mesh Agent, otherwise it continues walking like normal.

Now when we play the game, the knight enters the death state when defeated, like so:

### Improving Shooting Mechanics

At this point you might notice a problem….

…Okay, I know there are many problems, but there are two specifics problems I’m referring to.

1. The knight dies almost instantly whenever we shoot
2. When we shoot, we don’t really have anything happen to the enemy to make us feel we even shot them

So we’re going to fix these problems

Right now, we always shoot a raycast at the enemy knight whenever Update() detects that our mouse is held down.

So, let’s add a delay to our Player Shooting Controller script.

using UnityEngine;
public class PlayerShootingController : MonoBehaviour
{
public float Range = 100;
public float ShootingDelay = 0.1f;
    private Camera _camera;
private ParticleSystem _particle;
private float _timer;
    void Start () {
_camera = Camera.main;
_particle = GetComponentInChildren<ParticleSystem>();
Cursor.lockState = CursorLockMode.Locked;
_timer = 0;
}

void Update ()
{
_timer += Time.deltaTime;
        if (Input.GetMouseButton(0) && _timer >= ShootingDelay)
{
Shoot();
}
}
    private void Shoot()
{
_timer = 0;
Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
        if (Physics.Raycast(ray, out hit, Range, _shootableMask))
{
print("hit " + hit.collider.gameObject);
_particle.Play();
            EnemyHealth health = hit.collider.GetComponent<EnemyHealth>();
if (health != null)
{
health.TakeDamage(1);
}
}
}
}

Here’s the logic for what we added:

1. We created our time variables to figure out how long we must wait before we shoot again
2. In Update() if we waited long enough, we can fire again
3. Side note: I decided to move all of the shooting code into Shoot()
4. Inside Shoot() because the player fired, we’ll reset our timer and begin waiting until we can shoot again.

### Setting up the Game Objects

When we shoot our enemy knight, nothing really happens. He’ll just ignore you and continue walking towards you.

There are a lot of things we can do to make this better:

3. Push him back
4. All of the above

1) will be added in eventually, 2) might be done, but 3) is what I’m going to implement.

Every time we shoot the knight, we want to push it back. This way if a mob of them swarm at us, we’ll have to manage which one to shoot first.

This little feature took a LONG time to resolve.

The problem

Whenever we shoot an enemy, we want to push them back, however, the Nav Mesh Agent would override any changes we tried. Specifically, the knight will always continue moving forward.

The solution

We write some code that changes the velocity of the Nav Mesh Agent to go backwards for a couple of units.

However, when I did that, the knight continued running forward!

Why?

That’s a good question, one that I’m still investigating and hopefully find a solution by tomorrow.

### End of Day 13

For the first time ever today, I started on a problem, that I couldn’t solve in a day.

I’m expecting this to become more common as we start jumping deeper and deeper.

With that being said, today we fixed the player’s drifting problem by using drag and adding an enemy death animation when they run out of health.

Tomorrow I’ll continue investigating how I can push the enemy back.

See you all on Day 14! Or whenever I can figure out this knockback problem!

Original Day 13

Visit the main 100 Days of Unity VR Development page

Visit my homepage

There are no comments to display.

## Create an account

Register a new account

• ### Similar Content

• By ggenije
On picture 1 is actually what I get, but how to make it to look like pic 2?

• Hi,
I am using unitys mecanim system
I have a layer that controls movement ie idle -> run
it works fine when I press W I run forward with the animation via transform.position += anim.deltaPosition; // anim is on a child object that has the animator
I have a second layer for attack set to override 100%, on this layer I have just the head moving and is masked just for the neck up. it plays when I press the mouse button.

Now my problem is when I press W and mouse button, it plays both animations BUT it stops moving forward.
Theres no location key frames on the attack or any key frames on the root node for that matter.

Please tell me if I am being unclear.

Also I lost my other acc because I cant remember my pass or the email i used, is there a way I can get it back? like I say the account name and it tells me which email i used?

• Hey everyone! My name is Ryan.

Visualistic Studios is looking for experienced developers of all talents to join a game development team focused on completing contract work for compensation.

Work Description
Typically you will either be assisting the team or working on your own contract.
We usually bid $16-$25/h, however contracts can go above and below that so all pay grades are welcome, just be realistic.

Short Term Contracts
Long Term Contracts

We have the highest priority for these skills right now

Programming - Unity, Unreal Blueprints
Environment Artist
Character Artist
Character Animation
UI Artist
3D Asset Optimization

VR/Mobile experience is a plus.

The Process
All communication is done through discord. All tasks and design documents will be laid out in "HackNPlan" for organization.
Initially, you'll get in contact with me and answer a few questions so I can get a scope of your experience. Afterwards, our outreach team will start looking for jobs that fit your description. Nothing is guaranteed, but if we know you're interested we can start looking

Our Experience
For the past 3 years I've been working in game development contracting, and the past year I've been working full time from home. Since then, I've received more and more contracts and I'm now at the point that I have too many for myself to handle. This sparked the idea of creating a game development team for contract work! I've also been running my own hobby company for 5 years, and have a lot of experience in team management.

Get in contact!
Please fill out this form so we can get all of the information out of the way, then we'll get in contact with you!
Thank you everyone for reading, hope to hear from you soon!

• Hi there,
I'm working on an web RPG. This is not and action RPG.
The problem is I work full-time as a software developer and while I may get some code for the game done at work, I'm still a little short on time. So I'm looking for a second programmer to help me out. Please no beginners. I prefer working with someone who has built a full game (client, game server, web services, db)
Requirements:
Proficient in C# Proficient in .Net Core 2.X Experience with ASP.Net Core MVC Experience with ASP.Net Core Web API Experience with Unity 2018 Proficient in SQL and SQLite Proficient in EntityFramework Experience in AWS (RDS and EC2) Experience with IIS I'll handle the cost of any third-party services, domain names, etc. I'm just looking for a little help to get this game built in a reasonable amount of time. It will also be nice to bounce some ideas off each other.

• GameDaily.Biz spoke to Improbable about its new shortcuts to multiplayer game development for Unity and Unreal.

Improbable helps game developers build believable online worlds with its bespoke technology, SpatialOS. Now, that task is much easier and accessible for those building games on the technology with the recent release of the SpatialOS Game Development Kit (GDK) for Unity. With these kits, Improbable hopes that developers find it easier to create vast, dynamic and unique worlds.
This GDK for Unity includes a 200-gamer, first-person project that allows developers to experiment and tinker with their ideas for what their vision of a multiplayer game will look like.
GameDaily.Biz met with Improbable’s Head of Product Marketing, Paul Thomas, and Head of Comms, Daniel Nye Griffiths, to speak about the SpatialOS GDK for Unity, as well as the upcoming launch of the SpatialOS GDK for Unreal Engine.
In its first week, the SpatialOS GDK for Unity achieved over 2,000 developer sign ups to use it. “What we're trying to do is basically make it really fast for people to build multiplayer games,” said Thomas. “It comes with all the multiplayer networking so that developers don’t have to do any multiplayer networking. It comes with feature modules to allow [easy] solutions to common multiplayer problems, like player movement and shooting. And it comes with a cool starter project where you have 200 players in a free-for-all scenario. You can obviously use the power of SpatialOS to scale that project up to more players, with NPCs, and things like that. It gives people a really good base to start building multiplayer games.”
There are several games currently in development or early access that utilize SpatialOS. The first into Early Access was Spilt Milk Studios’ Lazarus, a space MMO where the player becomes a pilot in a universe that ends every week, complete with a map that’s twice the size of Austria. Additionally, Bossa Studios released its survival exploration game Worlds Adrift into Steam Early Access earlier this year.
Also using SpatialOS is Scavengers from Midwinter Entertainment, a studio founded by former 343 Industries studio head and Halo 4 Creative Director, Josh Holmes; the game is heavily inspired by his Halo 5: Guardians’ multiplayer mode, Warzone. Right alongside that company, Berlin-based Klang Studios is working on Seed, a simulation MMO that, according to its developers, lets players “interact and collaborate to create a world driven by real emotion and aspiration.”
According to Thomas, for those looking to use the SpatialOS GDK for Unity, there is no limit to  what their games can do with Improbable’s tech.
“What we're doing is expanding the possible gameplay you can do. Traditionally, when you make a multiplayer game, you're constrained by one single server. So you can say you have a 64-player game with a handful of NPCs or you could have a world that's 3km by 3km. With Spatial, you can go beyond that, test a much broader canvas to start thinking about different gameplay.”
“You can go for a massive online persistent MMO with 10,000 players and hundreds of thousands of NPCs, something very, very vast and big like that. But you can also have smaller experiences. For example, there's a lot of interesting space in just extending what you see in the Battle Royale genre and session-based gameplay.”
Thomas continued: “Our partners at Automaton have a game in development called Mavericks. The interesting thing there is they have a Battle Royale with 1,000 people, but what I really find interesting is the gameplay mechanics they've put in, like footprints so you can track people. They've added a cool fire propagation mechanic so you can start a fire that  spreads across the map and changes the world. Or you can add destructible buildings and things like that.”
“So I think even looking at smaller scale games, we add a lot of value in terms of the new gameplay you can start adding. I'm just interested to see what people do with this extra power - what they can come up with.”
While Battle Royale games and MMOs are obvious standouts for genres that best fit with SpatialOS, Thomas introduced some other ideas of genres that could benefit from the technology.
“I also think there's a space for very interesting MMORTSs as well,” he said. “An RTS where you have persistent systems, like telling AIs to do things and then coming back to them a week later and seeing what's happened is an interesting space.”
“I also see interesting mobile experiences that could come up. Having these worlds where you lay down some interesting things and then come back a few weeks later to see how they've evolved and changed, and the massive player interaction. Say for example with Pokemon Go, we can actually roam around the world and battle on the streets. I can see something like that working very well. Again, these are just ideas we've had and talked to people about. It's about giving people that flexibility and the ability to explore these ideas.”
Klang’s Seed
Griffiths added the possibility of events in a game that will have a massive, rippling, and lasting impact on its world as something that has people excited. One example he gives is how someone on one side of the map can do something that’ll have a knock-on effect for the rest of the world in real time.
“There's a whole bunch of different angles you can take, some of which are about much larger player numbers or a much larger map, but there are other things you can do which are taking a relatively constrained game experience, a smaller map, a smaller number of players and adding richness to the game as well.”
In fact, this is something that Thomas refers to as a “persistent in memory database,” meaning that for every object in the game world, there’s a history. Two examples cited by Thomas: “...a player could chop down a tree and that tree stays disappeared forever. Or a player can kill a big monster that was raiding a town and that town no longer gets raided by that monster, and this changes the dynamics of the world. Worlds can have a history. That means players can have a lot more meaning in these MMO worlds.”
“Normally in MMOs, they're kinda like roller coaster rides: you go into a dungeon, you kill the boss and that guy respawns. It all resets,” Thomas continues. “But in Spatial MMOs, you could have these persistent effects that should change the gameplay meaningfully for all the rest of the player base.”
“The other one I think that is interesting is the level of dynamism that you could have. So because you can have so much more server-side compute, you could potentially have NPCs roaming around the world changing their mind and deciding all of a sudden, 'oh, we're going to attack this player's base' or 'we're gonna go attack this town' and they have a lot more range and emotion and intelligence to them that you'd not see in other MMOs.
“Normally in MMOs, NPCs sit there tethered. You go near them and they come and attack you, you run away, and they go back to where they were. In a Spatial MMO, that NPC can trace you across the whole map or a group of them can decide to get together and attack someone..”

Next week, Improbable plans to launch its SpatialOS GDK for Unreal Engine, which will have a big focus on ease of use for access to Unreal, as well as a big emphasis on porting your projects to SpatialOS.
“One of the things we'll be trying to push is a porting guide so you'll be able to take your existing Unreal game, move it onto SpatialOS and then you can grow to expand it with new and extra gameplay,” says Thomas. “ You can bring across your existing Unreal game and it feels very, very native and similar to Unreal if you're familiar with Unreal.”
Griffiths continued, explaining how testing these experiences includes free cloud deployments, to a certain point. “If you're developing in SpatialOS in other ways, we provide a sandbox environment so you can get your game running. When you’re happy, you can port it over and sort of experiment with it in a free sandbox environment with a small number of cores to get started.”
Based on what we learned, Improbable’s SpatialOS GDK for Unity will give developers enhanced flexibility to produce more in depth and engaging videos games. That said, we look forward to catching up with the company in the near future to see how this exciting technology is being used in the different games that we play.
×