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

100 Days of VR: Day 8 Creating a Character in a First Person Shooter

Josh Chang

2957 views

Here we are on day 8! Yesterday we created a very simple map for a simple FPS feature.

Today, I went to look to see how we can move a character around in the scenery that was created.

Here’s what I got!

Creating our character

The first thing I figured out who was the “character”. Turns out for our game, our main character is someone we know well.

Here it is:

Camera-man-1024x401.png

That’s right its Main Camera! Who knew?

If we think about it, it does make sense.

The camera object is what we see when we run the game. In an FPS game, we see what our character sees. Which means our camera must be part of the character, specifically their eyes.

Setting up our character

The first thing we do is to create an Empty Game object that we will call Player then we’ll make our main camera a child of player.

I’d imagine when we want a character model, we would have the camera be right in front of the face of the model, but for now, we don’t need one.

Make sure the camera is set at position (0, 1, 0) and the Player position to be (5, 1, 5).

The X and Z position is so that we don’t start falling through the edge of our map and the Y value would give us some height, otherwise we would be facing the floor.

Next, we need to add a collider to our Game Object so that we won’t fall through the world when we start the game.

I created a Capsule Collider and I set the height to be 2 and left the rest as the same.

I’ve also attached a RigidBody component, because later on, we’re going to have to write some code to make our camera move when we click on our keyboard.

And here we are, our player character:

player-character-1024x298.png

And here’s what we’ll see when we play:

player-sight.png

If you want, you can give our character a Mesh Renderer and a Mesh Filter so that you can see where our character is in the Scene tab. We also get a nice little shadow!

Creating Movement for our Character

Now that we have a character, the next thing we have to do is to move it.

I found that Unity actually offers some very good built in FPS controls from this thread: How to make a first-person player for my game.

If you don’t have the fps scripts like in the thread, you can go to Assets > Import Package > Player to get these scripts.

After downloading them, all you have to do is attach the scripts to the Player game object.

However, since I’m doing this for learning, I’m going to attempt to write my own script to do something similar.

The first thing I’m going to do is create a new script called PlayerController, this will be used to control our player’s position based off of the user’s input.

I actually had to spend a lot of time working on this and searching on Google, but here are the results.

using UnityEngine;

public class PlayerController : MonoBehaviour {

    public float Speed = 3f;

    private Vector3 _movement;
    private Rigidbody _playerRigidBody;

    private void Awake()
    {
        _playerRigidBody = GetComponent<Rigidbody>();
    }
    

    private void FixedUpdate()
    {
        float horizontal = Input.GetAxisRaw("Horizontal");
        float vertical = Input.GetAxisRaw("Vertical");

        Move(horizontal, vertical);
    }

    private void Move(float horizontal, float vertical)
    {
        _movement = (vertical * transform.forward) + (horizontal * transform.right);
        _movement = _movement.normalized * Speed * Time.deltaTime;
        _playerRigidBody.MovePosition(transform.position + _movement);
    }
}

The code is pretty straight forward, here’s the flow:

  • In Awake() we get our RigidBody so we can move our player
  • In FixedUpdate(), we use GetAxisRaw() to get our horizontal and vertical movement so that we can detect if the user is moving left/right and up/down.
  • In Move() we’re given the movement directions. We want to create a movement vector that captures the direction from where the user is facing, which we achieve with transform.forward and transform.right. By multiplying everything together, we get the direction that the player should move based off of their inputs.
  • Finally we normalize our movement vector and then we move our position with our new Vector.

It’s important to note that we must use the RigidBody to move.

Before I was trying to move the player with transform.Translate, what I found out is that this function is the equivalent of teleportation. What happens is that if there are obstacles in front of the player, our character will just teleport past them.

I also want to emphasis that it’s important that we use transform.forward and transform.right especially once we start trying to get the camera to follow the mouse.

When we start rotating our character to follow the mouse, our vertical and horizontal values don’t give us the direction adjusted for which direction we’re facing.

For example, if we were to face forward and press W to move forward, we would move forward. However, if we were to turn 90 degrees to the right, and press W again, instead of moving forward like you’d expect, you would move to the left where “forward” use to be.

transform.forward gives us vector that the player is facing and then we multiply that with our vertical value which tells us if we’re moving forward or back. We do the same with transform.right and horizontal.

Rotating our Camera

The next problem after making our character move is trying to figure out how to get the camera to follow the mouse.

There were a lot of answers, however I think the best explanation is from this Youtube video: How to construct a simple First Person Controller.

I only took the snippet for the camera controller.

I made another class called MouseCameraController and attached it to our Main
Camera
.

The script allows us to we want to be able to view up and down with the camera without moving the character, but we want to change our player rotation value as we look horizontally.

Here’s the code:

using UnityEngine;

public class MouseCameraContoller : MonoBehaviour
{
    public float Sensitivity = 5.0f;
    public float Smoothing = 2.0f;

    private Vector2 _mouseLook;
    private Vector2 _smoothV;

    private GameObject _player;

    void Awake()
    {
        _player = transform.parent.gameObject;
    }

    // Update is called once per frame
    void Update () {
        Vector2 mouseDirection = new Vector2(Input.GetAxisRaw("Mouse X"), Input.GetAxisRaw("Mouse Y"));

        mouseDirection.x *= Sensitivity * Smoothing;
        mouseDirection.y *= Sensitivity * Smoothing;

        _smoothV.x = Mathf.Lerp(_smoothV.x, mouseDirection.x, 1f / Smoothing);
        _smoothV.y = Mathf.Lerp(_smoothV.y, mouseDirection.y, 1f / Smoothing);

        _mouseLook += _smoothV;
        _mouseLook.y = Mathf.Clamp(_mouseLook.y, -90, 90);

        transform.localRotation = Quaternion.AngleAxis(-_mouseLook.y, Vector3.right);
        _player.transform.rotation = Quaternion.AngleAxis(_mouseLook.x, _player.transform.up);
    }
}

There’s a lot of math to digest for this code, but let’s go through them.

Like mentioned, it’s important that the script is attached to the camera and not the main character body.

We want to rotate the characters body when we look left to right, but when we look up to down, we don’t want to rotate the body.

  • In our Start() function, we want to get the parent element (the Player Game Object) so we can rotate it as we turn.
  • In Update() we create a vector that would represent where our mouse is facing which we will use to determine where our camera will be facing by using our Mouse X and Mouse Y positions
  • Next we want to multiply the direction we created with 2 variables: Sensitivity and Smoothing
    1. Sensitivity is used to determine how big the vector of our mouseDirection would be. The higher the number, the more sensitive our mouse would be, allowing us to rotate more quickly.
    2. Smoothness is used to help us evenly move our camera from its starting location to the new location from the mouse location. We use lerp to help us make gradual movement instead of one massive movement
  • Once we calculate the new direction we’re facing into smoothV, we add that into our mouseLook variable which is where our character will be facing.
  • We make sure to clamp the y rotation, because we don’t want to be able to go from looking in front of us to behind us. It’s unnatural human anatomy.
  • Finally, for rotation. We want to rotate the localRotation of our camera, meaning we rotate the game object, relative to its parent.
    1. For example, if our player is facing 90 degree, if we were to set rotation of our camera to 90, we would be at 90, the same location. If we use localRotation, it would take in the fact our character is facing 90 degree and rotate 90 more.
    2. We create our angle by using our y value (the up and down) and rotating by the angle Vector3.right, which is the X axis.
  • Our last rotation is when we want to turn our player around instead of the camera. We don’t have to use localRotation, because the player doesn’t have a parent (which means it defaults to the game world as the parent), so we can just use rotation, though both would work.
    1. As for our rotation, we rotate our player by our left and right mouse movements using Vector3.up, which is the Y axis.

And that’s it! Play the game and you should be able to move your character around in the game world and bump into our environment that we setup.

Conclusion

Now wasn’t this short compared to the video tutorials?

Today we learned how to move and rotate the character around in the game screen.

It’s important to know that Unity provides a standard asset that makes movement easy for us, but I do think there’s value in being able to understand some of the inner workings of the code.

Either way, stay tune for Day 9, where we’ll hopefully start exploring how we can equip a gun in our player and maybe even start shooting something!

Original Day 8

Visit the main 100 days of VR 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 ggenije
      On picture 1 is actually what I get, but how to make it to look like pic 2?

    • By Mercutio604x
      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.
      Thanks in advance,
       
      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?
    • By tspartant
      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!
    • By addictCoderCS
      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.
       
      If you are interested, please send me an email: addictcodercs@gmail.com
       
       
    • By GameDev.net
      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..”

      Bossa Studios' Worlds Adrift
       

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

Important Information

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

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!