using CSNetwork.Protocols.RPCData; using System.Data; using System.Text; using TMPro; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.UI; using UnityEngine.Windows; public class CharacterCtrl : MonoBehaviour { [SerializeField] private TextMeshPro txtName; [SerializeField] private CharacterController controller; [SerializeField] private Animator animator; [SerializeField] private Joystick joystick; [SerializeField] private Button btnJump; [SerializeField] private Button btnRun; float playerSpeed = 5.0f; float jumpHeight = 1.5f; float gravityValue = -9.81f; StateAnim stateAnim = StateAnim.Idle; Vector3 playerVelocity; bool isGrounded = false; bool isRun = false; private void Start() { //btnJump.onClick.AddListener(HandleJump); } private void HandleJump() { if (isGrounded) { playerVelocity.y = Mathf.Sqrt(jumpHeight * -2f * gravityValue); SetAnimJump(); } } public void SetStatusRun(bool value) { if (!isGrounded) { Debug.LogError("Player not in ground"); return; } isRun = value; } public void InitCharacter(RoleInfo role) { string roleName = "(Error decoding name)"; if (role.name != null && role.name.ByteArray != null) { // Be careful with encoding, assume UTF8 is correct roleName = Encoding.UTF8.GetString( role.name.ByteArray, 0, role.name.Length ); } Vector3 pos = new Vector3(role.posx, role.posy, role.posz); if(txtName != null) { txtName.text = roleName; } transform.position = pos; Debug.LogError("Pos Character = " + pos); } private void Update() { isGrounded = controller.isGrounded; if (UnityEngine.Input.GetKeyDown(KeyCode.LeftShift)) { SetStatusRun(true); } if (UnityEngine.Input.GetKeyUp(KeyCode.LeftShift)) { SetStatusRun(false); } if (UnityEngine.Input.GetKeyDown(KeyCode.Space)) { HandleJump(); } if (isGrounded && playerVelocity.y < 0) { playerVelocity.y = 0f; } //float x = joystick.Horizontal; //float z = joystick.Vertical; //Vector3 move = new Vector3(x, 0, z); //move = Vector3.ClampMagnitude(move, 1f); //if (move != Vector3.zero) //{ // transform.forward = move; // if (isRun) // { // SetAnimRun(); // } // else // { // SetAnimWalk(); // } //} //else //{ // SetAnimIdle(); //} //playerVelocity.y += gravityValue * Time.deltaTime; //Vector3 finalMove = (move * playerSpeed) + (playerVelocity.y * Vector3.up); //controller.Move(finalMove * Time.deltaTime); } private void SetAnimIdle() { if(stateAnim == StateAnim.Idle || !isGrounded) { return; } stateAnim = StateAnim.Idle; animator.SetTrigger("Idle"); } private void SetAnimRun() { if (stateAnim == StateAnim.Run || !isGrounded) { return; } stateAnim = StateAnim.Run; animator.SetTrigger("Run"); } private void SetAnimWalk() { if (stateAnim == StateAnim.Walk || !isGrounded) { return; } stateAnim = StateAnim.Walk; animator.SetTrigger("Walk"); } private void SetAnimJump() { if (stateAnim == StateAnim.Jump) { return; } stateAnim = StateAnim.Jump; animator.SetTrigger("Idle"); } } public enum StateAnim { Idle = 1, Walk = 2, Run = 3, Jump = 4 }