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 Movement sprinting script problems.

Discussion in 'Scripting' started by unity_F1B9D874517F84E88860, Jun 19, 2023.

  1. unity_F1B9D874517F84E88860

    unity_F1B9D874517F84E88860

    Joined:
    Jun 16, 2023
    Posts:
    2
    hey! I'm having problems with my scripts.
    I followed brackeys "Third player movement" and "First player movement" tutorials. And tried to add ZeveonsHDs "unity tutorial / crouching + sprinting" but I can't seem to make it work.
    This is my current code:

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

    public class PlayerMovement : MonoBehaviour
    {

    public CharacterController controller;
    public Transform cam;

    public float speed = 12f;
    public float gravity = -9.8f;
    public float jumpHeight = 3f;

    public bool isSprinting = false;
    public float sprintingMultiplier;

    public float turnSmoothTime = 0.1f;
    float turnSmoothVelocity;


    public Transform groundCheck;
    public float groundDistance = 0.4f;
    public LayerMask groundMask;

    Vector3 velocity;
    bool isGrounded;

    // Update is called once per frame
    void Update()
    {
    isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask);

    if(isGrounded && velocity.y < 0)
    {
    velocity.y = -2f;
    }

    float horizontal = Input.GetAxisRaw("Horizontal");
    float vertical = Input.GetAxisRaw("Vertical");
    Vector3 direction = new Vector3(horizontal, 0f, vertical).normalized;

    if (direction.magnitude >= 0.1f)
    {
    float targetAngle = Mathf.Atan2(direction.x, direction.z) * Mathf.Rad2Deg + cam.eulerAngles.y;
    float angle = Mathf.SmoothDampAngle(transform.eulerAngles.y, targetAngle, ref turnSmoothVelocity, turnSmoothTime);
    transform.rotation = Quaternion.Euler(0f, angle, 0f);

    Vector3 moveDir = Quaternion.Euler(0f, targetAngle, 0f) * Vector3.forward;
    controller.Move(moveDir.normalized * speed * Time.deltaTime);
    }
    if(Input.GetButtonDown("Jump") && isGrounded)
    {
    velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity);
    }

    velocity.y += gravity * Time.deltaTime;

    controller.Move(velocity * Time.deltaTime);

    if (Input.GetKey("KeyCode.Leftshift"))
    {
    isSprinting = true;

    }
    else
    {
    isSprinting = false;
    }
    Vector3 movement = new Vector3();

    movement = x * transform.right + z * transform.forward;

    if (isSprinting == true)
    {
    movement *= sprintingMultiplier;
    }

    velocity.y += gravity * Time.deltaTime;

    controller.Move(movement * speed * Time.deltaTime);
    controller.Move(velocity * Time.deltaTime);
    }
    }

    In the console it tells me that 'x' and 'y' doesn't exist in the current context.
    Do I add another float? thanks!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    Throw this script out. It is based on a defective example and calls .Move() twice.

    If you persist with this script calling .Move() twice, you can expect endless problems.

    I wrote about this before: the Unity example code in the API no longer jumps reliably.

    If you call .Move() twice in one single frame, the grounded check may fail.

    I reported it to Unity via their docs feedback in October 2020. Apparently it is still broken:

    https://docs.unity3d.com/ScriptReference/CharacterController.Move.html

    Here is a work-around:

    https://forum.unity.com/threads/how...racter-movement-in-unity.981939/#post-6379746

    I recommend you also go to that same documentation page and ALSO report that the code is broken.

    When you report it, you are welcome to link the above workaround. One day the docs might get fixed.

    If you would prefer something more full-featured here is a super-basic starter prototype FPS based on Character Controller (BasicFPCC):

    https://forum.unity.com/threads/a-basic-first-person-character-controller-for-prototyping.1169491/

    That one has run, walk, jump, slide, crouch... it's crazy-nutty!!
     
  3. JustinNaicker

    JustinNaicker

    Joined:
    Jan 4, 2023
    Posts:
    47
  4. unity_F1B9D874517F84E88860

    unity_F1B9D874517F84E88860

    Joined:
    Jun 16, 2023
    Posts:
    2
    THANKS! Im new to unity I accualy started 3 days ago. I've only spend a few hours on it. Although I think my brain is gonna explode. Do you know any free simple tutorials or something? You seem skilled! thanks!

    Do you think I should fix the problem or follow the tutorial you talked about. I spent hours on this code, redoing it several times.
     
  5. Inxentas

    Inxentas

    Joined:
    Jan 15, 2020
    Posts:
    275
    Regarding the "don't call move twice" matter: what worked for me was to chop down the logic into multiple functions that each modify a private member Vector3. So one function determines the X / Z values for movement, while another modifies it's Y value for jumping, etc. Then the final one calls the Move() method on the Character Controller. The Update method would then look something like this. Note that my script is for an FPS controller.

    Code (CSharp):
    1. void Update()
    2.     {
    3.         this.isGrounded = cc.isGrounded;
    4.         ReadInput();
    5.         SetCamera();
    6.         SetMovement();
    7.         SetLookAt();
    8.         ActivateLookAt();
    9.     }
    First, I read axis input and generate axisH and axisV values.
    Secondly, I read the mouse input and generate a camera vector.
    Third, I combine the result of the above to determine a move direction. The Move() method is called at the end.
    Fourth, I determine what object the camera looks at, if any.
    Fifth, I check the input to see if the player is activating the looked at object.

    So if you wanted to include jumping and crouching, you could add methods of your own that modify the vector that's eventually fed into the Move() method. I split the methods up for ease of maintenaince, but the key point here is to make sure Move() is called only once per frame. I found the easiest way to do this is to have input change a private Vector3, and use this once per Update cycle to feed the Move() method.
     
  6. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,563
    I know something better... a strategy! You should be asking yourself... "Can I ... ?" and piece by piece put it together. It will not all come at once and every bit you do will help you connect more of the pieces in your mind, help you to be more effective.

    Watch how this guy did it:

    Imphenzia: How Did I Learn To Make Games: