Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice
  3. Join us on November 16th, 2023, between 1 pm and 9 pm CET for Ask the Experts Online on Discord and on Unity Discussions.
    Dismiss Notice
  4. Dismiss Notice

Third Person Camera Movement Script

Discussion in 'Scripting' started by NairelPrandini, Apr 2, 2020.

Thread Status:
Not open for further replies.
  1. NairelPrandini

    NairelPrandini

    Joined:
    Mar 31, 2018
    Posts:
    10

    hey i thought would be a good idea to share my script of free third person camera and movement since i had trouble finding some solid and straight forward scripts out there.

    i made two scripts one for the camera and other for the player using the character controller component but of corse you can adapt whatever you like.



    Camera Script:
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class CameraMove : MonoBehaviour
    6. {
    7.  
    8.     private const float YMin = -50.0f;
    9.     private const float YMax = 50.0f;
    10.  
    11.     public Transform lookAt;
    12.  
    13.     public Transform Player;
    14.  
    15.     public float distance = 10.0f;
    16.     private float currentX = 0.0f;
    17.     private float currentY = 0.0f;
    18.     public float sensivity = 4.0f;
    19.  
    20.  
    21.     // Start is called before the first frame update
    22.     void Start()
    23.     {
    24.      
    25.  
    26.     }
    27.  
    28.     // Update is called once per frame
    29.     void LateUpdate()
    30.     {
    31.  
    32.         currentX += Input.GetAxis("Mouse X") * sensivity * Time.deltaTime;
    33.         currentY += Input.GetAxis("Mouse Y") * sensivity * Time.deltaTime;
    34.  
    35.         currentY = Mathf.Clamp(currentY, YMin, YMax);
    36.  
    37.         Vector3 Direction = new Vector3(0, 0, -distance);
    38.         Quaternion rotation = Quaternion.Euler(currentY, currentX, 0);
    39.         transform.position = lookAt.position + rotation * Direction;
    40.  
    41.         transform.LookAt(lookAt.position);
    42.  
    43.      
    44.  
    45.     }
    46. }
    47.  
    Player Movement Script:

    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerMove : MonoBehaviour
    6. {
    7.  
    8.  
    9.     CharacterController Controller;
    10.  
    11.     public float Speed;
    12.  
    13.     public Transform Cam;
    14.  
    15.  
    16.     // Start is called before the first frame update
    17.     void Start()
    18.     {
    19.  
    20.         Controller = GetComponent<CharacterController>();
    21.  
    22.     }
    23.  
    24.     // Update is called once per frame
    25.     void Update()
    26.     {
    27.  
    28.         float Horizontal = Input.GetAxis("Horizontal") * Speed * Time.deltaTime;
    29.         float Vertical = Input.GetAxis("Vertical") * Speed * Time.deltaTime;
    30.  
    31.         Vector3 Movement = Cam.transform.right * Horizontal + Cam.transform.forward * Vertical;
    32.         Movement.y = 0f;
    33.  
    34.  
    35.  
    36.         Controller.Move(Movement);
    37.  
    38.         if (Movement.magnitude != 0f)
    39.         {
    40.             transform.Rotate(Vector3.up * Input.GetAxis("Mouse X") * Cam.GetComponent<CameraMove>().sensivity * Time.deltaTime);
    41.  
    42.  
    43.             Quaternion CamRotation = Cam.rotation;
    44.             CamRotation.x = 0f;
    45.             CamRotation.z = 0f;
    46.  
    47.             transform.rotation = Quaternion.Lerp(transform.rotation, CamRotation, 0.1f);
    48.  
    49.         }
    50.     }
    51.  
    52. }
    53.  
    Hope i helped someone out there
    if you want to share any improvements to my script feel free to do so
     
    ERVIN8, zinzsoft, Albemag and 13 others like this.
  2. HernandoNJ

    HernandoNJ

    Joined:
    May 13, 2018
    Posts:
    75
    Hi there.
    It would be really appreciated if you add comments and a quick youtube video showing how it can be implemented.
    Thanks.
     
    NairelPrandini likes this.
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,779
    I put it together because I was curious. I didn't comment on it because it is all super straightforward.

    Enclosed please find the setup I used. I had to adjust mouse sensitivity WAY up to make it usable.

    If you have questions about a line of code, work through the documentation for the functions you're unsure about, or come ask a pointed question here.

    @Alsda_Gamer Hope you don't mind me repackaging your code and posting it back here.
     

    Attached Files:

  4. sStarS

    sStarS

    Joined:
    Mar 27, 2020
    Posts:
    19
    can this be used for a mobile game with 1 left joystick for movement and to move camera left/right/up/down by touching the screen with your finger? I cant seem to find a good one ( or at least a working one..) that doesn't involve using another characters scripts from unity store
     
  5. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,779
    It can but you might have better luck starting from something designed for touch screen, since the above is designed for mouse movement.

    In my proximity_buttons project I have a small demo called
    DemoCameraRotatedControls.unity
    that sorta does this, but it is more of a top-down isometric controller, although you could probably hack it to do what you want.

    proximity_buttons is presently hosted at these locations:

    https://bitbucket.org/kurtdekker/proximity_buttons

    https://github.com/kurtdekker/proximity_buttons

    https://gitlab.com/kurtdekker/proximity_buttons

    https://sourceforge.net/projects/proximity-buttons/
     
  6. sStarS

    sStarS

    Joined:
    Mar 27, 2020
    Posts:
    19
    thank you, i'll take a look, after 3 days looking for a proper touch movement for my camera I will try anithing
     
  7. crakuser

    crakuser

    Joined:
    Aug 13, 2020
    Posts:
    1
    it says i am missing a behavior is there any way to fix it?
     
  8. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,779
    Since you didn't post what behavior, all I can say is "yes, add that behavior!"

    How to report problems productively in the Unity3D forums:

    http://plbm.com/?p=220

    Help us to help you.
     
    willsucc likes this.
  9. sStarS

    sStarS

    Joined:
    Mar 27, 2020
    Posts:
    19
    i dont know if this is what yout want but

    this tutorial worked for me ( you have to read a few comments cause they will help solve some issues ) but
    everithing works perfectly ( except the camera does not move up and down ( but i fixed that once with raycast . ill see if it gets fixed once i write a raycast again , last time i did it for desktop but this time i'm doing it for mobile)
     
    Last edited by a moderator: Feb 15, 2022
    HernandoNJ likes this.
  10. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    So I followed this one video from brackey (Unity third person camera) but i feel like i messed something up
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class thridpersonmovement : MonoBehaviour
    6. {
    7.     public CharacterController Controller;
    8.     public float speed = 6f;
    9.  
    10.     public Transform CamObj;
    11.     public float turnSmoothTime = 0.1f;
    12.     float turnSmoothVelocity;
    13.  
    14.     public float gravity = -9.81f;
    15.     public float jumpHeight = 3;
    16.     Vector3 velocity;
    17.     bool isGrounded;
    18.  
    19.     public Transform groundCheck;
    20.     public float groundDistance = 0.4f;
    21.     public LayerMask groundMask;
    22.  
    23.     private WFSC wStep;
    24.     private AFSS aStep;
    25.     private SFSS sStep;
    26.     private DFSS dStep;
    27.  
    28.  
    29.     public GameObject footManage;
    30.     public void Awake()
    31.     {
    32.          wStep = footManage.GetComponent<WFSC>();
    33.          aStep = footManage.GetComponent<AFSS>();
    34.         sStep = footManage.GetComponent<SFSS>();
    35.          dStep = footManage.GetComponent<DFSS>();
    36.     }
    37.  
    38.     // Update is called once per frame
    39.     void Update()
    40.     {
    41.         bool M1 = wStep.IsMoving;
    42.         bool M2 = aStep.Moving;
    43.         bool M3 = sStep.isMove;
    44.         bool M4 = dStep.Move;
    45.  
    46.         if(M1 == true && GetComponent<AudioSource>().isPlaying == false && isGrounded == true)
    47.         {
    48.             GetComponent<AudioSource>().Play();
    49.         }
    50.         else if (M2 == true && GetComponent<AudioSource>().isPlaying == false && isGrounded == true)
    51.         {
    52.             GetComponent<AudioSource>().Play();
    53.         }
    54.         else if(M3 == true && GetComponent<AudioSource>().isPlaying == false && isGrounded == true)
    55.         {
    56.             GetComponent<AudioSource>().Play();
    57.         }
    58.         else if(M1 == true && GetComponent<AudioSource>().isPlaying == false && isGrounded == true)
    59.         {
    60.             GetComponent<AudioSource>().Play();
    61.         }
    62.         else
    63.         {
    64.             GetComponent<AudioSource>().Stop();
    65.         }
    66.  
    67.  
    68.         //jump
    69.         isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);
    70.  
    71.         if (isGrounded && velocity.y < 0)
    72.         {
    73.             velocity.y = -2f;
    74.         }
    75.  
    76.         if (Input.GetButtonDown("Jump") && isGrounded)
    77.         {
    78.             velocity.y = Mathf.Sqrt(jumpHeight * -2 * gravity);
    79.         }
    80.         //gravity
    81.         velocity.y += gravity * Time.deltaTime;
    82.         Controller.Move(velocity * Time.deltaTime);
    83.  
    84.         float horizontal = Input.GetAxisRaw("Horizontal");
    85.         float vertical = Input.GetAxisRaw("Vertical");
    86.  
    87.         Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;
    88.  
    89.         if(direction.magnitude >= 0.1f)
    90.         {
    91.             float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg * CamObj.eulerAngles.y;
    92.             //Atan is an angle that start's at 0 at the x axis but in Unity the 0 is forward
    93.  
    94.             float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
    95.             transform.rotation = Quaternion.Euler(0f, angle, 0f);
    96.  
    97.             Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
    98.             Controller.Move(moveDir.normalized * speed * Time.deltaTime);
    99.  
    100.         }
    101.  
    102.     }
    103. }
     
  11. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,779
    This is a terrible feeling to have I am sure.

    Again I suggest you read: how to report problems productively in the Unity3D forums:

    http://plbm.com/?p=220

    Specifically, I highlight this paragraph:

    Step 3. Identify at least the ballpark area where the error is in your code. Extract the relevant section of code, as little as you think will show the problem, and post it here. If you don’t post code, we can’t help you. If you post massive amounts of code, we’ll assume you’re not even trying to be helpful. If nothing is happening, use Debug.Log() to find out if your code is even running.​
     
  12. NitroZoron

    NitroZoron

    Joined:
    Jun 29, 2020
    Posts:
    42
    okay I will
     
  13. votlesword

    votlesword

    Joined:
    Oct 28, 2020
    Posts:
    3
    Welp it seems that it turn off psychict
     
    mcagarretson and Rotor133 like this.
  14. GOODJEDIRYAN

    GOODJEDIRYAN

    Joined:
    May 2, 2021
    Posts:
    1
    I used your unity package and set up everything, but it doesn't work for me.
     
  15. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,779
    How to report your problem productively in the Unity3D forums:

    http://plbm.com/?p=220

    How to understand compiler and other errors and even fix them yourself:

    https://forum.unity.com/threads/ass...3-syntax-error-expected.1039702/#post-6730855

    If you post a code snippet, ALWAYS USE CODE TAGS:

    How to use code tags: https://forum.unity.com/threads/using-code-tags-properly.143875/

    What is often happening in these cases is one of the following:

    - the code you think is executing is not actually executing at all
    - the code is executing far EARLIER or LATER than you think
    - the code is executing far LESS OFTEN than you think
    - the code is executing far MORE OFTEN than you think
    - the code is executing on another GameObject than you think it is

    To help gain more insight into your problem, I recommend liberally sprinkling Debug.Log() statements through your code to display information in realtime.

    Doing this should help you answer these types of questions:

    - is this code even running? which parts are running? how often does it run? what order does it run in?
    - what are the values of the variables involved? Are they initialized? Are the values reasonable?
    - are you meeting ALL the requirements to receive callbacks such as triggers / colliders (review the documentation)

    Knowing this information will help you reason about the behavior you are seeing.

    You can also put in Debug.Break() to pause the Editor when certain interesting pieces of code run, and then study the scene

    You could also just display various important quantities in UI Text elements to watch them change as you play the game.

    If you are running a mobile device you can also view the console output. Google for how on your particular mobile target.

    Here's an example of putting in a laser-focused Debug.Log() and how that can save you a TON of time wallowing around speculating what might be going wrong:

    https://forum.unity.com/threads/coroutine-missing-hint-and-error.1103197/#post-7100494
     
  16. poomayil

    poomayil

    Joined:
    Oct 7, 2021
    Posts:
    1
    Ok. I have very big question?
    how to make a left and right controls for android and ios??
    For example:
    Left controls have a transparent for rotate a camera control , jump button etc....
    Right controls have a joystick for walking and some buttons....
    But I want:
    First question: first show a joystick. And I press any ware to came joystick there, with on left side on display only
    Second question : I will rotate a camera in right side only
    And finally : I want aim in mid point on display

    Please solve this problem
     
  17. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,779
    Please stop posting to old threads.

    You are going to solve the problem yourself. Start here:

    Imphenzia / imphenzia - super-basic Unity tutorial:



    Jason Weimann:



    Brackeys super-basic Unity Tutorial series:



    Sebastian Lague Intro to Game Development with Unity and C#:

     
Thread Status:
Not open for further replies.