Make it so that when performing an attack when pressing the Control key. Switching to…
- User
Make it so that when performing an attack when pressing the Control key. Switching to other animations (other than falling) should not be possible until the strike/attack animation is completed. using System.Collections; using System.Collections.Generic; using UnityEditor.Experimental.GraphView; using UnityEngine;
[RequireComponent(typeof(CharacterController))] [RequireComponent(typeof(Animator))] public class ThirdPersonMovement : MonoBehaviour { [SerializeField] private Transform _camera; [SerializeField] private MovementCharacter _characteristics; private float _vertical, _horizontal, _run; private readonly string STR_VERTICAL = "Vertical"; private readonly string STR_HORIZONTAL = "Horizontal"; private readonly string STR_RUN = "Run"; private readonly string STR_JUMP = "Jump"; private readonly string STR_ATTACK = "Attack"; private const float DISTANCE_OFFFSET_CAMERA = 5f; private CharacterController _controller; private Animator _animator; private Vector3 _direction; private Quaternion _look; private Vector3 TargerRotate => _camera.forward * DISTANCE_OFFFSET_CAMERA; private bool Idle => _horizontal == 0.0f && _vertical == 0.0f;
codeprivate void Start() { _controller = GetComponent<CharacterController>(); _animator = GetComponent<Animator>(); Cursor.visible = _characteristics.VisibleCursor; } private void Update() { Movement(); Rotate(); } private void Movement() { if(_controller.isGrounded) { _horizontal = Input.GetAxis(STR_HORIZONTAL); _vertical = Input.GetAxis(STR_VERTICAL); _run = Input.GetAxis(STR_RUN); _direction = transform.TransformDirection(_horizontal, 0, _vertical).normalized; PlayAnimation(); Jump(); Attack(); } _direction.y -= _characteristics.Gravity * Time.deltaTime; float speed = _run * _characteristics.RunSpeed + _characteristics.MovementSpeed; Vector3 dir = _direction * speed * Time.deltaTime; dir.y = _direction.y; _controller.Move(dir); } private void Attack() { if (Input.GetKeyDown(KeyCode.LeftControl)) { _animator.Play("Attack"); // Trigger the attack animation } } private void Jump() { if(Input.GetButtonDown(STR_JUMP)) { _animator.SetTrigger(STR_JUMP); _direction.y += _characteristics.JumpForce; } } private void Rotate() { if(Idle) return; Vector3 target = TargerRotate; target.y = 0; _look = Quaternion.LookRotation(target); float speed = _characteristics.AngularSpeed * Time.deltaTime; transform.rotation = Quaternion.RotateTowards(transform.rotation, _look, speed); } private void PlayAnimation() { float horizontal = _run * _horizontal + _horizontal; float vertical = _run * _vertical + _vertical; _animator.SetFloat(STR_VERTICAL, vertical); _animator.SetFloat(STR_HORIZONTAL, horizontal); } - Assistant