Day 130 — Setting up a 3rd Person 3D Project
Hey and welcome!
The next project here is going to be a shorter one compared to the other’s we’ve done but it’s going to be a fun one! With this article we’ll look into getting the project set up and some basic movement in place for our Player object.
We’re going to start things off by creating a new 3D project in Unity and calling it something along the lines of 3rd Person Survival Project.
Now create a floor by adding in a cube and stretching it out and then add in a capsule object and call this Player.
Next is the movement, we’re going to be doing the Character Controller route when handling movement this time so go ahead and add the component for that to your Player object and then create a Player script to attach with this code in it:
private CharacterController _controller;[SerializeField]
private float _speed = 6.0f;
[SerializeField]
private float _jumpHeight = 8.0f;
[SerializeField]
private float _gravity = 20.0f;private Vector3 _direction;
private Vector3 _velocity;void Start()
{
_controller = GetComponent<CharacterController>();
if (_controller == null)
{
Debug.LogError("Character Controller is null");
}
}void Update()
{
if (_controller.isGrounded == true)
{
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
_direction = new Vector3(horizontal, 0, vertical);
_velocity = _direction * _speed; if (Input.GetKeyDown(KeyCode.Space))
{
_velocity.y = _jumpHeight;
}
}
_velocity.y -= _gravity * Time.deltaTime; _controller.Move(_velocity * Time.deltaTime);
}
You should be good and familiar with the code here at this point as we’re just creating the logic for movement using WASD and Arrow Keys as well as creating our own gravity and ability to jump.
Last thing to do now is to get your camera to follow the player and adjust its position to give us a 3rd person view. Drag and drop your main camera into your Player object so that it’s a child object and this will make the camera follow the player about.
Once you’ve done that go ahead and move your camera’s position so that the player is in the center and that you’re just barely unable to see the bottom of the player. When you’re happy with the position go ahead and rotate the camera on the x axis so that it’s looking down on the player a little bit while making sure the bottom is hidden. I set my x rotation to 15 for this.
With that all done your project is now set up and ready for what’s planned ahead!