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. Dismiss Notice

Question Character Controller Not Working As Intended

Discussion in 'Scripting' started by SamuraiBanger, Sep 25, 2023.

  1. SamuraiBanger

    SamuraiBanger

    Joined:
    Sep 25, 2023
    Posts:
    3
    I used a character controller based movement script i had learned from a brackeys tutorial but it was intender for a different style of 3rd person where the player rotation is independent from camera rotation but i wanted to have the camera follow the player y rotation and it did and after i added the lines to make the controller move in the direction the camera is facing forwards and backwards are working completely fine but when i move sideways it also moves backwards a little and makes a full circle if i hold down right or left for long enough instead of just moving sideways (ofcourse relative to camera) ive tried a lot of things but i cant seem to find a fix
    here's the script:

    using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;

    public class Controller : MonoBehaviour
    {
    public CharacterController controller;
    public GameObject cam;

    [SerializeField] float speed;

    float vertical;
    float horizontal;
    Vector3 dir;

    void Start()
    {
    controller = GetComponent<CharacterController>();
    cam = GameObject.FindGameObjectWithTag("MainCamera");
    }

    void Update()
    {
    vertical = Input.GetAxisRaw("Vertical");
    horizontal = Input.GetAxisRaw("Horizontal");
    dir = new Vector3(horizontal, 0, vertical).normalized;

    if (dir.magnitude > 0.1f)
    {
    float targetAngle = Mathf.Atan2(dir.x, dir.z) * Mathf.Rad2Deg + cam.transform.rotation.eulerAngles.y;
    Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;

    controller.Move(moveDir.normalized * speed * Time.deltaTime);
    }
    float camRotY = cam.transform.rotation.eulerAngles.y;
    controller.transform.rotation = Quaternion.Euler(0, camRotY, 0);
    }
    }
     
  2. zulo3d

    zulo3d

    Joined:
    Feb 18, 2023
    Posts:
    541
    I suspect you need to calibrate your gamepad.

    A simple controller script:

    Code (CSharp):
    1. using UnityEngine;
    2. public class SimpleController : MonoBehaviour
    3. {
    4.  
    5. CharacterController controller;
    6. [SerializeField] float speed;
    7.  
    8.     void Start()
    9.     {
    10.         controller = GetComponent<CharacterController>();
    11.     }
    12.  
    13.     void Update()
    14.     {
    15.         Vector3 moveDir=((transform.right*Input.GetAxisRaw("Horizontal"))+(transform.forward*Input.GetAxisRaw("Vertical"))).normalized;
    16.         controller.Move(moveDir.normalized * speed * Time.deltaTime);
    17.     }
    18. }
    19.  
     
  3. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,711
    Controlling player direction based on camera direction is almost certainly incorrect.

    Just start with some basic third person controller tutorials. Make sure you're doing tutorials correctly.

    If it's just camera you're concerned with, focus on tutorials that handle that. Camera work is often handled by Cinemachine these days.

    There's even a dedicated forum: https://forum.unity.com/forums/cinemachine.136/

    If you insist on making your own camera controller, the simplest way to do it is to think in terms of two Vector3 points in space: where the camera is LOCATED and where the camera is LOOKING.

    Code (csharp):
    1. private Vector3 WhereMyCameraIsLocated;
    2. private Vector3 WhatMyCameraIsLookingAt;
    3.  
    4. void LateUpdate()
    5. {
    6.   cam.transform.position = WhereMyCameraIsLocated;
    7.   cam.transform.LookAt( WhatMyCameraIsLookingAt);
    8. }
    Then you just need to update the above two points based on your GameObjects, no need to fiddle with rotations.


    Tutorials and example code are great, but keep this in mind to maximize your success and minimize your frustration:

    How to do tutorials properly, two (2) simple steps to success:

    Step 1. Follow the tutorial and do every single step of the tutorial 100% precisely the way it is shown. Even the slightest deviation (even a single character!) generally ends in disaster. That's how software engineering works. Every step must be taken, every single letter must be spelled, capitalized, punctuated and spaced (or not spaced) properly, literally NOTHING can be omitted or skipped.

    Fortunately this is the easiest part to get right: Be a robot. Don't make any mistakes.
    BE PERFECT IN EVERYTHING YOU DO HERE!!


    If you get any errors, learn how to read the error code and fix your error. Google is your friend here. Do NOT continue until you fix your error. Your error will probably be somewhere near the parenthesis numbers (line and character position) in the file. It is almost CERTAINLY your typo causing the error, so look again and fix it.

    Step 2. Go back and work through every part of the tutorial again, and this time explain it to your doggie. See how I am doing that in my avatar picture? If you have no dog, explain it to your house plant. If you are unable to explain any part of it, STOP. DO NOT PROCEED. Now go learn how that part works. Read the documentation on the functions involved. Go back to the tutorial and try to figure out WHY they did that. This is the part that takes a LOT of time when you are new. It might take days or weeks to work through a single 5-minute tutorial. Stick with it. You will learn.

    Step 2 is the part everybody seems to miss. Without Step 2 you are simply a code-typing monkey and outside of the specific tutorial you did, you will be completely lost. If you want to learn, you MUST do Step 2.

    Of course, all this presupposes no errors in the tutorial. For certain tutorial makers (like Unity, Brackeys, Imphenzia, Sebastian Lague) this is usually the case. For some other less-well-known content creators, this is less true. Read the comments on the video: did anyone have issues like you did? If there's an error, you will NEVER be the first guy to find it.

    Beyond that, Step 3, 4, 5 and 6 become easy because you already understand!

    Finally, when you have errors, don't post here... just go fix your errors! Here's how:

    Remember: NOBODY here memorizes error codes. That's not a thing. The error code is absolutely the least useful part of the error. It serves no purpose at all. Forget the error code. Put it out of your mind.

    The complete error message contains everything you need to know to fix the error yourself.

    The important parts of the error message are:

    - the description of the error itself (google this; you are NEVER the first one!)
    - the file it occurred in (critical!)
    - the line number and character position (the two numbers in parentheses)
    - also possibly useful is the stack trace (all the lines of text in the lower console window)

    Always start with the FIRST error in the console window, as sometimes that error causes or compounds some or all of the subsequent errors. Often the error will be immediately prior to the indicated line, so make sure to check there as well.

    Look in the documentation. Every API you attempt to use is probably documented somewhere. Are you using it correctly? Are you spelling it correctly? Are you structuring the syntax correctly? Look for examples!

    All of that information is in the actual error message and you must pay attention to it. Learn how to identify it instantly so you don't have to stop your progress and fiddle around with the forum.
     
  4. SamuraiBanger

    SamuraiBanger

    Joined:
    Sep 25, 2023
    Posts:
    3
    im not using a gamepad but thanks
     
  5. SamuraiBanger

    SamuraiBanger

    Joined:
    Sep 25, 2023
    Posts:
    3
    I am using cinemachine and the problem is not the camera moving wrong but the player controller itself, sorry if I wasn't clear enough abt my issue, I thought the script would be enough
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,711
    You are forcing the player to rotate (face in) the same direction as the Camera. Is that the problem you are having?

    See what I wrote above, the very first line:

    Again, doing that almost always feels wrong, ESPECIALLY when your camera is being controlled externally.
     
  7. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    3,524
    You have a circular feedback loop between your player and your camera. The camera follows the player and the player follows the camera. The main issue ist that you have at least a 1 frame delay between them because you do the player rotation after your movement.

    As Kurt said, you shouldn't have such circular dependencies. It makes it very difficult to get a consistent behaviour. Especially when you later decide that you want to add some kind of smoothing to any of the movements