Search Unity

Question starter 3rd person can't teleport? (webgl)

Discussion in 'Scripting' started by s5904062663182, Feb 28, 2023.

  1. s5904062663182

    s5904062663182

    Joined:
    Aug 8, 2022
    Posts:
    9
    I'm creating the 3D WebGL project and trying to use the teleport menu with third person character asset.
    i don't know it's a bug or some weird thing in my code. that sometime the player won't teleport.
    as the menu panel's script I have
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4. using StarterAssets;
    5.  
    6. public class MainMenu : MonoBehaviour
    7. {
    8.     public GameObject panalMain;
    9.     public GameObject panalSelectChar;
    10.     public GameObject panalMap;
    11.     public ThirdPersonController thirdPersonController;
    12.  
    13.     private void Start() {
    14.         Cursor.visible = true;
    15.         Cursor.lockState = CursorLockMode.None;
    16.  
    17.         panalMain.gameObject.SetActive(true);
    18.         panalSelectChar.gameObject.SetActive(false);
    19.         panalMap.gameObject.SetActive(false);
    20.         thirdPersonController.enabled = false;
    21.     }
    22.  
    23.     public void OnclickPlay(){
    24.         Debug.Log("OnclickPlay");
    25.         panalMain.gameObject.SetActive(false);
    26.         panalSelectChar.gameObject.SetActive(true);
    27.  
    28.     }
    29.     public void OnclickSetting(){
    30.         Debug.Log("OnclickSetting");
    31.      
    32.     }
    33.     public void OnclickHowTo(){
    34.         Debug.Log("OnclickHowTo");
    35.      
    36.     }
    37.     public void OnclickCha1(){
    38.         Debug.Log("OnclickCha1");
    39.  
    40.  
    41.         panalMain.gameObject.SetActive(false);
    42.         panalSelectChar.gameObject.SetActive(false);
    43.         panalMap.gameObject.SetActive(true);
    44.      
    45.      
    46.     }
    47.     public void OnclickCha2(){
    48.         Debug.Log("OnclickCha2");
    49.  
    50.  
    51.         panalMain.gameObject.SetActive(false);
    52.         panalSelectChar.gameObject.SetActive(false);
    53.         panalMap.gameObject.SetActive(true);
    54.      
    55.     }
    56.  
    57.     public void OnSelectPoint(){
    58.         Debug.Log("OnSelectPoint");
    59.  
    60.         Cursor.visible = false;
    61.         Cursor.lockState = CursorLockMode.Locked;
    62.         panalMap.gameObject.SetActive(false);
    63.         thirdPersonController.enabled = true;
    64.     }
    65.  
    66. }

    I just add thirdPersonController.enabled = true/false; to block the movement while using menu.

    i have 3 empty gameobject to make the teleport location.

    i create the teleport script and
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerTeleport : MonoBehaviour
    6. {
    7.     public Transform[] points;
    8.     public GameObject player;
    9.  
    10.     public void Deploy(int index){
    11.         Debug.Log("Deploy");
    12.  
    13.  
    14.         StartCoroutine(DeployObj(points[index].position));
    15.     }
    16.  
    17.     IEnumerator DeployObj(Vector3 pos){
    18.         yield return new WaitForSeconds(0.2f);
    19.         player.transform.position = pos;
    20.     }
    21. }
    thank you in advance
     
    Last edited: Mar 1, 2023
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,735
    Depending on what is inside the ThirdPersonController, you may need to tell something inside it to move.

    This might apply if it is based on CharacterController or Rigidbody, OR even if it tracks its own position internally rather than respecting the Transform arbitrarily.
     
  3. s5904062663182

    s5904062663182

    Joined:
    Aug 8, 2022
    Posts:
    9
    in ThirdPersonController they have
    Code (CSharp):
    1.  using UnityEngine;
    2. #if ENABLE_INPUT_SYSTEM
    3. using UnityEngine.InputSystem;
    4. #endif
    5.  
    6. /* Note: animations are called via the controller for both the character and capsule using animator null checks
    7. */
    8.  
    9. namespace StarterAssets
    10. {
    11.     [RequireComponent(typeof(CharacterController))]
    12. #if ENABLE_INPUT_SYSTEM
    13.     [RequireComponent(typeof(PlayerInput))]
    14. #endif
    15.     public class ThirdPersonController : MonoBehaviour
    16.     {
    17.         [Header("Player")]
    18.         [Tooltip("Move speed of the character in m/s")]
    19.         public float MoveSpeed = 2.0f;
    20.  
    21.         [Tooltip("Sprint speed of the character in m/s")]
    22.         public float SprintSpeed = 5.335f;
    23.  
    24.         [Tooltip("How fast the character turns to face movement direction")]
    25.         [Range(0.0f, 0.3f)]
    26.         public float RotationSmoothTime = 0.12f;
    27.  
    28.         [Tooltip("Acceleration and deceleration")]
    29.         public float SpeedChangeRate = 10.0f;
    30.  
    31.         public AudioClip LandingAudioClip;
    32.         public AudioClip[] FootstepAudioClips;
    33.         [Range(0, 1)] public float FootstepAudioVolume = 0.5f;
    34.  
    35.         [Space(10)]
    36.         [Tooltip("The height the player can jump")]
    37.         public float JumpHeight = 1.2f;
    38.  
    39.         [Tooltip("The character uses its own gravity value. The engine default is -9.81f")]
    40.         public float Gravity = -15.0f;
    41.  
    42.         [Space(10)]
    43.         [Tooltip("Time required to pass before being able to jump again. Set to 0f to instantly jump again")]
    44.         public float JumpTimeout = 0.50f;
    45.  
    46.         [Tooltip("Time required to pass before entering the fall state. Useful for walking down stairs")]
    47.         public float FallTimeout = 0.15f;
    48.  
    49.         [Header("Player Grounded")]
    50.         [Tooltip("If the character is grounded or not. Not part of the CharacterController built in grounded check")]
    51.         public bool Grounded = true;
    52.  
    53.         [Tooltip("Useful for rough ground")]
    54.         public float GroundedOffset = -0.14f;
    55.  
    56.         [Tooltip("The radius of the grounded check. Should match the radius of the CharacterController")]
    57.         public float GroundedRadius = 0.28f;
    58.  
    59.         [Tooltip("What layers the character uses as ground")]
    60.         public LayerMask GroundLayers;
    61.  
    62.         [Header("Cinemachine")]
    63.         [Tooltip("The follow target set in the Cinemachine Virtual Camera that the camera will follow")]
    64.         public GameObject CinemachineCameraTarget;
    65.  
    66.         [Tooltip("How far in degrees can you move the camera up")]
    67.         public float TopClamp = 70.0f;
    68.  
    69.         [Tooltip("How far in degrees can you move the camera down")]
    70.         public float BottomClamp = -30.0f;
    71.  
    72.         [Tooltip("Additional degress to override the camera. Useful for fine tuning camera position when locked")]
    73.         public float CameraAngleOverride = 0.0f;
    74.  
    75.         [Tooltip("For locking the camera position on all axis")]
    76.         public bool LockCameraPosition = false;
    77.  
    78.         // cinemachine
    79.         private float _cinemachineTargetYaw;
    80.         private float _cinemachineTargetPitch;
    81.  
    82.         // player
    83.         private float _speed;
    84.         private float _animationBlend;
    85.         private float _targetRotation = 0.0f;
    86.         private float _rotationVelocity;
    87.         private float _verticalVelocity;
    88.         private float _terminalVelocity = 53.0f;
    89.  
    90.         // timeout deltatime
    91.         private float _jumpTimeoutDelta;
    92.         private float _fallTimeoutDelta;
    93.  
    94.         // animation IDs
    95.         private int _animIDSpeed;
    96.         private int _animIDGrounded;
    97.         private int _animIDJump;
    98.         private int _animIDFreeFall;
    99.         private int _animIDMotionSpeed;
    100.  
    101. #if ENABLE_INPUT_SYSTEM
    102.         private PlayerInput _playerInput;
    103. #endif
    104.         private Animator _animator;
    105.         private CharacterController _controller;
    106.         private StarterAssetsInputs _input;
    107.         private GameObject _mainCamera;
    108.  
    109.         private const float _threshold = 0.01f;
    110.  
    111.         private bool _hasAnimator;
    112.  
    113.         private bool IsCurrentDeviceMouse
    114.         {
    115.             get
    116.             {
    117. #if ENABLE_INPUT_SYSTEM
    118.                 return _playerInput.currentControlScheme == "KeyboardMouse";
    119. #else
    120.                 return false;
    121. #endif
    122.             }
    123.         }
    124.  
    125.  
    126.         private void Awake()
    127.         {
    128.             // get a reference to our main camera
    129.             if (_mainCamera == null)
    130.             {
    131.                 _mainCamera = GameObject.FindGameObjectWithTag("MainCamera");
    132.             }
    133.         }
    134.  
    135.         private void Start()
    136.         {
    137.             _cinemachineTargetYaw = CinemachineCameraTarget.transform.rotation.eulerAngles.y;
    138.            
    139.             _hasAnimator = TryGetComponent(out _animator);
    140.             _controller = GetComponent<CharacterController>();
    141.             _input = GetComponent<StarterAssetsInputs>();
    142. #if ENABLE_INPUT_SYSTEM
    143.             _playerInput = GetComponent<PlayerInput>();
    144. #else
    145.             Debug.LogError( "Starter Assets package is missing dependencies. Please use Tools/Starter Assets/Reinstall Dependencies to fix it");
    146. #endif
    147.  
    148.             AssignAnimationIDs();
    149.  
    150.             // reset our timeouts on start
    151.             _jumpTimeoutDelta = JumpTimeout;
    152.             _fallTimeoutDelta = FallTimeout;
    153.         }
    154.  
    155.         private void Update()
    156.         {
    157.             _hasAnimator = TryGetComponent(out _animator);
    158.  
    159.             JumpAndGravity();
    160.             GroundedCheck();
    161.             Move();
    162.         }
    163.  
    164.         private void LateUpdate()
    165.         {
    166.             CameraRotation();
    167.         }
    168.  
    169.         private void AssignAnimationIDs()
    170.         {
    171.             _animIDSpeed = Animator.StringToHash("Speed");
    172.             _animIDGrounded = Animator.StringToHash("Grounded");
    173.             _animIDJump = Animator.StringToHash("Jump");
    174.             _animIDFreeFall = Animator.StringToHash("FreeFall");
    175.             _animIDMotionSpeed = Animator.StringToHash("MotionSpeed");
    176.         }
    177.  
    178.         private void GroundedCheck()
    179.         {
    180.             // set sphere position, with offset
    181.             Vector3 spherePosition = new Vector3(transform.position.x, transform.position.y - GroundedOffset,
    182.                 transform.position.z);
    183.             Grounded = Physics.CheckSphere(spherePosition, GroundedRadius, GroundLayers,
    184.                 QueryTriggerInteraction.Ignore);
    185.  
    186.             // update animator if using character
    187.             if (_hasAnimator)
    188.             {
    189.                 _animator.SetBool(_animIDGrounded, Grounded);
    190.             }
    191.         }
    192.  
    193.         private void CameraRotation()
    194.         {
    195.             // if there is an input and camera position is not fixed
    196.             if (_input.look.sqrMagnitude >= _threshold && !LockCameraPosition)
    197.             {
    198.                 //Don't multiply mouse input by Time.deltaTime;
    199.                 float deltaTimeMultiplier = IsCurrentDeviceMouse ? 1.0f : Time.deltaTime;
    200.  
    201.                 _cinemachineTargetYaw += _input.look.x * deltaTimeMultiplier;
    202.                 _cinemachineTargetPitch += _input.look.y * deltaTimeMultiplier;
    203.             }
    204.  
    205.             // clamp our rotations so our values are limited 360 degrees
    206.             _cinemachineTargetYaw = ClampAngle(_cinemachineTargetYaw, float.MinValue, float.MaxValue);
    207.             _cinemachineTargetPitch = ClampAngle(_cinemachineTargetPitch, BottomClamp, TopClamp);
    208.  
    209.             // Cinemachine will follow this target
    210.             CinemachineCameraTarget.transform.rotation = Quaternion.Euler(_cinemachineTargetPitch + CameraAngleOverride,
    211.                 _cinemachineTargetYaw, 0.0f);
    212.         }
    213.  
    214.         private void Move()
    215.         {
    216.             // set target speed based on move speed, sprint speed and if sprint is pressed
    217.             float targetSpeed = _input.sprint ? SprintSpeed : MoveSpeed;
    218.  
    219.             // a simplistic acceleration and deceleration designed to be easy to remove, replace, or iterate upon
    220.  
    221.             // note: Vector2's == operator uses approximation so is not floating point error prone, and is cheaper than magnitude
    222.             // if there is no input, set the target speed to 0
    223.             if (_input.move == Vector2.zero) targetSpeed = 0.0f;
    224.  
    225.             // a reference to the players current horizontal velocity
    226.             float currentHorizontalSpeed = new Vector3(_controller.velocity.x, 0.0f, _controller.velocity.z).magnitude;
    227.  
    228.             float speedOffset = 0.1f;
    229.             float inputMagnitude = _input.analogMovement ? _input.move.magnitude : 1f;
    230.  
    231.             // accelerate or decelerate to target speed
    232.             if (currentHorizontalSpeed < targetSpeed - speedOffset ||
    233.                 currentHorizontalSpeed > targetSpeed + speedOffset)
    234.             {
    235.                 // creates curved result rather than a linear one giving a more organic speed change
    236.                 // note T in Lerp is clamped, so we don't need to clamp our speed
    237.                 _speed = Mathf.Lerp(currentHorizontalSpeed, targetSpeed * inputMagnitude,
    238.                     Time.deltaTime * SpeedChangeRate);
    239.  
    240.                 // round speed to 3 decimal places
    241.                 _speed = Mathf.Round(_speed * 1000f) / 1000f;
    242.             }
    243.             else
    244.             {
    245.                 _speed = targetSpeed;
    246.             }
    247.  
    248.             _animationBlend = Mathf.Lerp(_animationBlend, targetSpeed, Time.deltaTime * SpeedChangeRate);
    249.             if (_animationBlend < 0.01f) _animationBlend = 0f;
    250.  
    251.             // normalise input direction
    252.             Vector3 inputDirection = new Vector3(_input.move.x, 0.0f, _input.move.y).normalized;
    253.  
    254.             // note: Vector2's != operator uses approximation so is not floating point error prone, and is cheaper than magnitude
    255.             // if there is a move input rotate player when the player is moving
    256.             if (_input.move != Vector2.zero)
    257.             {
    258.                 _targetRotation = Mathf.Atan2(inputDirection.x, inputDirection.z) * Mathf.Rad2Deg +
    259.                                   _mainCamera.transform.eulerAngles.y;
    260.                 float rotation = Mathf.SmoothDampAngle(transform.eulerAngles.y, _targetRotation, ref _rotationVelocity,
    261.                     RotationSmoothTime);
    262.  
    263.                 // rotate to face input direction relative to camera position
    264.                 transform.rotation = Quaternion.Euler(0.0f, rotation, 0.0f);
    265.             }
    266.  
    267.  
    268.             Vector3 targetDirection = Quaternion.Euler(0.0f, _targetRotation, 0.0f) * Vector3.forward;
    269.  
    270.             // move the player
    271.             _controller.Move(targetDirection.normalized * (_speed * Time.deltaTime) +
    272.                              new Vector3(0.0f, _verticalVelocity, 0.0f) * Time.deltaTime);
    273.  
    274.             // update animator if using character
    275.             if (_hasAnimator)
    276.             {
    277.                 _animator.SetFloat(_animIDSpeed, _animationBlend);
    278.                 _animator.SetFloat(_animIDMotionSpeed, inputMagnitude);
    279.             }
    280.         }
    281.  
    282.         private void JumpAndGravity()
    283.         {
    284.             if (Grounded)
    285.             {
    286.                 // reset the fall timeout timer
    287.                 _fallTimeoutDelta = FallTimeout;
    288.  
    289.                 // update animator if using character
    290.                 if (_hasAnimator)
    291.                 {
    292.                     _animator.SetBool(_animIDJump, false);
    293.                     _animator.SetBool(_animIDFreeFall, false);
    294.                 }
    295.  
    296.                 // stop our velocity dropping infinitely when grounded
    297.                 if (_verticalVelocity < 0.0f)
    298.                 {
    299.                     _verticalVelocity = -2f;
    300.                 }
    301.  
    302.                 // Jump
    303.                 if (_input.jump && _jumpTimeoutDelta <= 0.0f)
    304.                 {
    305.                     // the square root of H * -2 * G = how much velocity needed to reach desired height
    306.                     _verticalVelocity = Mathf.Sqrt(JumpHeight * -2f * Gravity);
    307.  
    308.                     // update animator if using character
    309.                     if (_hasAnimator)
    310.                     {
    311.                         _animator.SetBool(_animIDJump, true);
    312.                     }
    313.                 }
    314.  
    315.                 // jump timeout
    316.                 if (_jumpTimeoutDelta >= 0.0f)
    317.                 {
    318.                     _jumpTimeoutDelta -= Time.deltaTime;
    319.                 }
    320.             }
    321.             else
    322.             {
    323.                 // reset the jump timeout timer
    324.                 _jumpTimeoutDelta = JumpTimeout;
    325.  
    326.                 // fall timeout
    327.                 if (_fallTimeoutDelta >= 0.0f)
    328.                 {
    329.                     _fallTimeoutDelta -= Time.deltaTime;
    330.                 }
    331.                 else
    332.                 {
    333.                     // update animator if using character
    334.                     if (_hasAnimator)
    335.                     {
    336.                         _animator.SetBool(_animIDFreeFall, true);
    337.                     }
    338.                 }
    339.  
    340.                 // if we are not grounded, do not jump
    341.                 _input.jump = false;
    342.             }
    343.  
    344.             // apply gravity over time if under terminal (multiply by delta time twice to linearly speed up over time)
    345.             if (_verticalVelocity < _terminalVelocity)
    346.             {
    347.                 _verticalVelocity += Gravity * Time.deltaTime;
    348.             }
    349.         }
    350.  
    351.         private static float ClampAngle(float lfAngle, float lfMin, float lfMax)
    352.         {
    353.             if (lfAngle < -360f) lfAngle += 360f;
    354.             if (lfAngle > 360f) lfAngle -= 360f;
    355.             return Mathf.Clamp(lfAngle, lfMin, lfMax);
    356.         }
    357.  
    358.         private void OnDrawGizmosSelected()
    359.         {
    360.             Color transparentGreen = new Color(0.0f, 1.0f, 0.0f, 0.35f);
    361.             Color transparentRed = new Color(1.0f, 0.0f, 0.0f, 0.35f);
    362.  
    363.             if (Grounded) Gizmos.color = transparentGreen;
    364.             else Gizmos.color = transparentRed;
    365.  
    366.             // when selected, draw a gizmo in the position of, and matching radius of, the grounded collider
    367.             Gizmos.DrawSphere(
    368.                 new Vector3(transform.position.x, transform.position.y - GroundedOffset, transform.position.z),
    369.                 GroundedRadius);
    370.         }
    371.  
    372.         private void OnFootstep(AnimationEvent animationEvent)
    373.         {
    374.             if (animationEvent.animatorClipInfo.weight > 0.5f)
    375.             {
    376.                 if (FootstepAudioClips.Length > 0)
    377.                 {
    378.                     var index = Random.Range(0, FootstepAudioClips.Length);
    379.                     AudioSource.PlayClipAtPoint(FootstepAudioClips[index], transform.TransformPoint(_controller.center), FootstepAudioVolume);
    380.                 }
    381.             }
    382.         }
    383.  
    384.         private void OnLand(AnimationEvent animationEvent)
    385.         {
    386.             if (animationEvent.animatorClipInfo.weight > 0.5f)
    387.             {
    388.                 AudioSource.PlayClipAtPoint(LandingAudioClip, transform.TransformPoint(_controller.center), FootstepAudioVolume);
    389.             }
    390.         }
    391.     }
    392. }
    oh... i write it wrong it's "third person character" asset
    I'm reading that because of build-in controller that make it not teleport I will try this one first
     
    Last edited: Mar 1, 2023
  4. s5904062663182

    s5904062663182

    Joined:
    Aug 8, 2022
    Posts:
    9
    after i add
    Code (CSharp):
    1. CharacterController cc = thePlayer.GetComponent<CharacterController>();
    2. cc.enabled = false;
    3. thePlayer.transform.position = warpTarget.transform.position;
    4. cc.enabled = true;
    to teleport script like this
    Code (CSharp):
    1. using System.Collections;
    2. using System.Collections.Generic;
    3. using UnityEngine;
    4.  
    5. public class PlayerTeleport : MonoBehaviour
    6. {
    7.     public Transform[] points;
    8.     public GameObject player;
    9.     public CharacterController cc;
    10.  
    11.     public void Deploy(int index){
    12.         Debug.Log("Deploy");
    13.         cc = player.GetComponent<CharacterController>();
    14.  
    15.         StartCoroutine(DeployObj(points[index].position)); // always use StartCoroitine use to call IEnumerator funtions
    16.     }
    17.  
    18.     IEnumerator DeployObj(Vector3 pos){
    19.         cc.enabled = false;
    20.         yield return new WaitForSeconds(0.2f); //wait before load because of bug
    21.         player.transform.position = pos;
    22.         cc.enabled = true;
    23.     }
    24. }
    now there's a warning like this

    Code (CSharp):
    1. CharacterController.Move called on inactive controller
    2. UnityEngine.CharacterController:Move (UnityEngine.Vector3)
    3. StarterAssets.ThirdPersonController:Move () (at Assets/StarterAssets/ThirdPersonController/Scripts/ThirdPersonController.cs:271)
    4. StarterAssets.ThirdPersonController:Update () (at Assets/StarterAssets/ThirdPersonController/Scripts/ThirdPersonController.cs:161)
    is that because I turn off the CharacterController? will this cause the problem in the future?
     
  5. LEFOREL_

    LEFOREL_

    Joined:
    Jan 20, 2023
    Posts:
    1
    Hey! I'm currently going through the same issue. Did you find any solution to teleport the character ?