Jump to content
  • Advertisement
  • entries
    44
  • comments
    19
  • views
    2423

100 Days of VR: Day 10 Creating An Enemy

Josh Chang

549 views

Welcome to a very special day of my 100 days of VR. Day 10! That’s right. We’re finally in the double digits!

It’s been an enjoyable experience so far working with Unity, especially now that I know a bit more about putting together a 3D game now.

We haven’t made it into the actual VR aspects of the game, but we were able to get *some* foundational skills for Unity, which I’m sure will help translate into the skills needed to create a real VR experience.

We’re starting to get the hang of what we can use in Unity to make a game. Yesterday, we created the beginning of the shooting mechanism.

Currently, whenever we hit something, we just print out what we hit. Today we’re going to go in and create an enemy player that we can shoot and make some fixes.

Updating the Shooting Code

The first thing I would like to fix is that when we shoot, we shoot at whatever our cursor is pointing at, which is kind of weird.

Looking the cursor to the middle

This can be easily fixed by adding:

Cursor.lockState = CursorLockMode.Locked;

To Start() in our PlayerShootingController script

We’ll have something like this:

void Start () {
    _camera = Camera.main;
    _particle = GetComponentInChildren<ParticleSystem>();
    Cursor.lockState = CursorLockMode.Locked;
}

Now when we try to play the game, our cursor will be gone. It’ll be in the middle of the screen, we just can’t see it.

Adding a Crosshair

At this point, we want some indicator to show where our “center” is.

To do this, we’re going to create an UI crosshair that we’ll put right in the middle.

In the hierarchy, add an Image which we will call Crosshair. By doing this Unity will also create a Canvas for us. We’ll call that HUD.

By default, our crosshair is already set in the middle, but it’s too big. Let’s make it smaller. In the Rect Transform, I set our image to have Width and Height 10, 10.

You should have something like this now:

Before we do anything else, we need to make sure that our mouse collider doesn’t send a raycast onto our UI elements.

In HUD, attach a Canvas Group component and from there, uncheck Interactable and Blocks Raycasts. As you might recall, the Canvas Groupcomponent will allow us to apply these 2 settings to its children without us having to manually do it ourselves.

Go ahead and play around with it. If we observe our console, whenever we fire we hit where our little “crosshair” is located at.

Creating our Enemy

So now we fixed our cursor to be the center, the next thing we need to do is to create an enemy.

We’ll improve upon this, but for now, let’s create our first enemy! A cube!

Add a Cube to your hierarchy, name it Enemy, and then drag it near our player.

Boom! First enemy!

Now currently, nothing really happens when you shoot at it, so let’s fix it by adding an enemy health script. We’ll call it EnemyHealth

Here’s what the code looks like:

 
using UnityEngine;
public class EnemyHealth : MonoBehaviour
{
    public float Health = 10;
	
    public void TakeDamage(float damage)
    {
        Health -= damage;
        if (Health <= 0)
        {
            Destroy(gameObject);
        } 
    }
}
 

It’s relatively simple:

  1. We have our health
  2. We have a public function that we’ll call our player hits the enemy that’ll decrease the enemies HP
  3. When it reaches 0, we make our enemy disappear

Now before we update our script, let’s make some optimizations to our raycast.

Go to our Enemy game object and then set its layer to Shootable if it doesn’t exist (which it most likely doesn’t), create a new layer, call it Shootable, and then assign it to the Enemy layout.

Now let’s go back to our PlayerShootingController and grab the EnemyHealth script that we just created and make them take damage:

 
using UnityEngine;
public class PlayerShootingController : MonoBehaviour
{
    public float Range = 100;
    private Camera _camera;
    private ParticleSystem _particle;
    private LayerMask _shootableMask;
	void Start () {
		_camera = Camera.main;
	    _particle = GetComponentInChildren<ParticleSystem>();
	    Cursor.lockState = CursorLockMode.Locked;
	    _shootableMask = LayerMask.GetMask("Shootable");
	}
	
	void Update () {
	    if (Input.GetMouseButton(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);
	            }
                }
	    }
	}
}
 

The changes we’ve done is very similar to what we have seen before with Survival Shooter, but here’s the addition that we added:

  1. We created our LayerMask for our Shootable layer and passed it into our Raycast function
    1. Note, I tried to use an int at first to represent our LayerMask, but for some reason, the Raycast ignored the int. From searching around online, I found that instead of using the int representation, we should just try the actual LayerMask object. When I gave that a try, it worked…. So yay?
  2. Next, when we hit an object, which at this point, can only be Enemy, we grab the EnemyHealth script that we added and then we make the enemy take 1 damage. Do this 10 times and the enemy will die.

Now with this script attached to our enemy, shoot our cube 10 times (which should happen really fast), and then BOOM, gone.

Conclusion

And that’s about as far as I got for Day 10! Today was a bit brief, because I didn’t get much time to work, but I think we made some good progress!

We created the basis for an enemy and added a basic crosshair UI that we can use. Tomorrow, I’m going to start looking into seeing how to add an enemy from the Unity Asset Store into the game.

Until then, I’ll see you all in day 11!

Original Day 10

Visit the 100 Days of VR main page



0 Comments


Recommended Comments

There are no comments to display.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Advertisement
  • Advertisement
  • Blog Entries

  • Similar Content

    • By JustACicada
      Random Number God has been updated to v1.1.0.
      This is an incremental (although not idle) game about defeating randomized robots by rolling dice and playing cards that alter those dice and their effects.
      Other than performance fixes, the game has been rebalanced from the ground up. Now it should progress in a more fluid fashion. An option to reset the game with a significant boost to your power has been added, allowing you to advance further than you could before.
      There is also now an option to significantly speed up battle animations. Once you learn the rules of the game, a battle can easily take <2 min.
      Windows, Linux: https://justacicada.itch.io/random-number-god
      Android: https://play.google.com/store/apps/details?id=samuelVazquez.randomNumberGod


    • By Jamesgz
      Hey my dudes,
      Me and 4 friends are third year compsci students. Three of us are pretty good at drawing. We are hoping to make a 2d roguelite game with unity during the next few months. We are still brainstorming. At the moment, my idea is to create a card roguelite game:
      First, you would need to choose 2 heroes to enter the dungeon with the goal of finding a treasure. The treasure found gives you extra bonus in later runs. You can choose between mage, gunner, rogue, paladin, warrior and fighter. Each hero has their own unique cards. And there are common cards that every heroes can get(like hearthstone).
      The progression system would be like slay the spire’s. You can choose your own path, but every paths leads to the boss. It would use procedural generation. After defeating an enemy, you get to choose a new card out of the three options. There would be shops, random events, elite enemies, etc
      The combat system is where i need some suggestions on. There would be two piles of deck. One for each hero. I can think of two good combat systems:
      1. Before every enemy encounters, you can choose what cards to use from your deck. Cards not used would not get discarded. Cards are drawn from the deck only if they break or due to special card’s effect. Every card have a durability number. Ones the durability reach zero, the card would break and can no longer be used. Events/enemies can modify the durability of the cards.
      2. Card not used this turn would get discarded. Once the deck is empty, the discard pile gets shuffled and copied to the deck. Card/item effects can increase the number of cards you draw.
      How can I make the game more interesting? Any suggestions would be appreciated.
    • By horror_man
      Hello, I'm currently searching for a talented and passionate programmer to create a small but great horror game that would take around 3 months to be done.
       
      About the game: The game would be a sci-fi/post-apocalyptic survival horror 3D game with FPS (First person shooter) mechanics and an original setting and story based in a book (which I'm writing) scene, where a group of prisoners are left behind in an abandoned underground facility. It would play similar to Dead Space combined with Penumbra and SCP: Secret Laboratory, with the option of playing solo or multiplayer.
       
      Engine that'd be used to create the game: Unity
       
      About me: I'm a music composer with 4 years of experience and I'm fairly new in this game development world, and I'm currently leading the team that'd be creating this beautiful and horrifying game. I decided that making the book which I'm writing into a game would be really cool, and I got more motivated about doing so some time ago when I got a bunch of expensive Unity assets for a very low price. However, I researched about how to do things right in game development so I reduced the scope of it as much as I could so that's why this game is really based in a scene of the book and not the entire thing (and also that's why it would take 3 months). Also I'm currently learning how to use Unity and how to model things with Blender.
       
      Our team right now consists of: Me (Game Designer, Creator, Music Composer, Writer), 3 3D Modelers, 1 Sound Effect Designer, 1 Concept Artist and 1 Programmer.
       
      Who am I looking for:
      - A programmer that's experienced in C# and with Unity.
       
      Right now the game is very early in its development (GDD is completed and all 3D Items, Music and Sound Effects are completed).
       
      If you are interested in joining, contributing or have questions about the project then let's talk. You can message me in Discord: world_creator#9524
    • By kcirkl
      Hello, 
      So, I'm aware this may be a broad question with a vast variety in the anwser. However, I am a game design student that works professionally for a large engineering company conducting software configuration. Naturally, I'm curious about the path ahead and I'm desperately gathering information on the overall process of developement with Unity. Are there professional resources available that can outline the processes and functions of the engine, and what can be used to interact with it? I'm looking for options other than the official documentation. I have already jumped into that. Thanks!
    • By tspartant
      Hey everyone! My name is Ryan and I am the founder of Visualistic Studios, LLC. 
      I'm looking for experienced developers interested in short term and long term contracting. 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. I have at least another full time job's worth of programming offers, and around 30-80 hours a month for 3D modeling/animation. I also am in need of a UI artist, so if you're talented please contact me! I have contracts using Unity as well as Unreal Engine 4, so if you can program in either please contact me. 
      If you are interested in working on these contracts, please send me links to your work and you hourly rate. (Most contracts range be between 18-25$/h, but please provide your normal hourly rate)
      You can get ahold of me through email - "ryan.hobbs@visualisticstudios.com", or Discord "TSpartanT#4670"
       
      Thank you everyone for reading, hope to hear from you soon!
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!