• entries
44
19
• views
2496

100 Days of VR: Day 16 Using A Real Gun Model In Unity

696 views

Welcome back to Day 16! Today we’re going to go fix some of the assets for the game.

Specifically, today I want to:

1. Use a real gun asset
2. Add the shooting effect back in

Do you know what that means?

We’re going to go back to the Unity asset store to find new assets! Let’s get started!

Setting Up a Real Gun Asset

I looked around for a gun asset and I found a great machine gun model to use!

I found this great looking Machine Guns asset.

The first thing we should do is replace our cube with our gun asset.

In the folder FreeMachineGun: FreeMachineGun > Prefabs we find MachineGun_00. Drag the prefab into our hierarchy and make it a child of our Main Camera game object, making it the child of our previous Gun game object.

I made some configuration to my transform to make it fit here’s what I have, however you might have to eyeball it yourself.

• Position: (0.25, -0.5, 0.75)
• Rotation: (0. 90, 0)

You should have something like this:

I like how straightforward this is!

Setting up the Gun Animation to Run When We Shoot

Right now, when we left click, our gun will start shooting and spilling out ammos.

You might be thinking: “Wow! This model is amazing it even has the shooting code done for me!”

Unfortunately, it isn’t that easy. What we’re seeing is the particle effect of the gun that we activate in our PlayerShootingController.

You might also notice that after we shoot, our particle effect never stops either, that’s because in our code, we never had to stop our particle effect before.

Before we go in and fix this, let’s first understand the states to our animation.

For us to interact with the animation of a model, we must go to the Animatortab to set animation states and transitions.

Select MachineGun_00 in the hierarchy pane and then go to the Animatortab.

If the Animator tab isn’t available for you can find it in Window > Animator

Here’s what we see.

We have 3 trigger parameters to work with:

• DoOpen
• Shoot

As for our state, we have 4 states:

• Default
• MachingGun_open
• MachineGun_shoot

Looking at our transitions…

In default:

• Shoot transition to the MachineGun_shoot
• DoOpen transitions to MachineGun_open

In MachineGun_shoot

• Shoot transition back to default
• DoOpen transitions to MachineGun_open

In MachineGun_open:

• Shoot transition to the MachineGun_shoot
• DoOpen transitions back to default

• After the animation time is finish we transition to default

Now that we understand how the trigger logic works, we can work on the shooting script.

Now I don’t know what the DoOpen animation is for, however we don’t need it for the game in my mind. We just need to shoot and reload.

Creating the Code to Shoot

Now that we have the assets in place, we’re going to write the code to use it.

The first thing is that for some reason, I attached the PlayerShootingController to the camera. I’m going to move that to our new MachineGun_00 game object.

If you created a new PlayerShootingController, make sure the settings are:

• Range: 100
• Shooting Delay: 0.2
• Shot Sfx Clips: Machine_Gunfire_01

Before going to the code, I had to think about the general cases that I would encounter for our animation to work.

It’s interesting to think about it, because we have 3 states that our gun can be in: default, shooting, and reloading. Now imagine how much more complicated if we had to transition between even more!

When I first started coding, I just had the general case, press R to reload and then shoot.

However, there were problems where my code would put me in permanent shooting animation mode among many other things.

There were some that I had to encounter, here were the specific animation cases I had to consider:

1. Hit reload while we’re not doing anything
2. Hit reload while we’re shooting
4. Never let go of our mouse before we shoot, reload, and then hold on until after we’re done reloading

Without any further waiting, here’s our code:


using UnityEngine;
public class PlayerShootingController : MonoBehaviour
{
public float Range = 100;
public float ShootingDelay = 0.1f;
public AudioClip ShotSfxClips;
private Camera _camera;
private ParticleSystem _particle;
private float _timer;
private AudioSource _audioSource;
private Animator _animator;
private bool _isShooting;
void Start () {
_camera = Camera.main;
_particle = GetComponentInChildren<ParticleSystem>();
Cursor.lockState = CursorLockMode.Locked;
_timer = 0;
SetupSound();
_animator = GetComponent<Animator>();
_isShooting = false;
}

void Update ()
{
_timer += Time.deltaTime;
{
Shoot();
if (!_isShooting)
{
TriggerShootingAnimation();
}
}
else if (!Input.GetMouseButton(0))
{
StopShooting();
if (_isShooting)
{
TriggerShootingAnimation();
}
}
if (Input.GetKeyDown(KeyCode.R))
{
}
}
{
StopShooting();
_isShooting = false;
}
private void TriggerShootingAnimation()
{
_isShooting = !_isShooting;
_animator.SetTrigger("Shoot");
}
private void StopShooting()
{
_audioSource.Stop();
_particle.Stop();
}
private void Shoot()
{
_timer = 0;
Ray ray = _camera.ScreenPointToRay(Input.mousePosition);
RaycastHit hit = new RaycastHit();
_audioSource.Play();
_particle.Play();
if (Physics.Raycast(ray, out hit, Range, _shootableMask))
{
print("hit " + hit.collider.gameObject);
EnemyHealth health = hit.collider.GetComponent<EnemyHealth>();
EnemyMovement enemyMovement = hit.collider.GetComponent<EnemyMovement>();
if (enemyMovement != null)
{
enemyMovement.KnockBack();
}
if (health != null)
{
health.TakeDamage(1);
}
}
}
// called from the animation finished
{
}
private void SetupSound()
{
_audioSource.volume = 0.2f;
_audioSource.clip = ShotSfxClips;
}
}


There’s been a lot of changes and addition to the code, but in general here’s the flow:

1. We created more variables to keep track of what state we’re in. Currently we’re using Booleans, however I think using Enums to represent our state might be a better idea, especially if we have more states to keep track of.
2. In Start() we initialize our new boolean states
3. In Update(), while we’re not reloading and we hit Shoot, if we haven’t started shooting, we’ll start our shooting animation in TriggerShootingAnimation() and we’ll run our shooting logic in Shoot()
4. Whenever we let go of our mouse, we’ll go to the else statement in Update() and stop our shooting animation and run our stop shooting logic in StopShooting() which stops our music and particle effect
5. A side note: in Shoot(), I started the particle effect when we hit something with the raycast, we want it to always run whenever we shoot.
6. In Update() when we want to reload, we press R and we’ll go into StartReloading(), here we would trigger our reload animation to start and disable our shooting so the players can’t continue shooting.
7. We have a public function ReloadFinish() that tells us we’re down reloading. We’re going to have to go to the animation for our machine gun and add an event to run this function whenever we’re done reloading.

So now that we have our code in place, let’s add the event into our reload animation to run our ReloadFinish() code when the animation finishes.

To do that, select MachineGun_00 and select the Animation tab.

If you don’t have the Animation tab, you can open it by going to Window -> Animation.

Here’s what we will have at the end:

In the animation tab:

1. Select MachineGun_reload as our animation
2. Go to frame 68
3. Click the add event button below our frame number
4. Select ReloadFinish() as the function to run once we get to that frame

With all of this in place, we’ll be able to reload now when we hit R and then resume normal shooting controls after the animation ends.

Conclusion

There we go! Today we added a real gun asset to replace our fake cube gun. As you can see, it wasn’t that bad and a lot of the things we did, we already learned from the Zombie Shooter tutorial we did at the end.

With our gun in place, we’re done now, right? WRONG!

Back when I was doing my Survival shooter post, Scouting Ninja commented to me on how shooting really works and it turns out that the raycast we create isn’t actually coming directly from the screen.

It’s coming from the muzzle of our gun to the middle of the screen.

Tomorrow, I’m going to investigate how to shoot a raycast from our gun muzzle instead of directly from our screen!

Until then, I’ll see you all in Day 17!

Source: Day 16

Visit the 100 Days of Unity VR Development main page.

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.
×