using UnityEngine; public class PlayerMovement : MonoBehaviour { [Header("Movement Settings")] public float walkSpeed = 5f; public float runSpeed = 10f; public float jumpHeight = 2f; public float gravity = -19.62f; [Header("Ground Check")] public Transform groundCheck; public float groundDistance = 0.4f; public LayerMask groundMask; [Header("Animation")] public Animator animator; private CharacterController controller; private Vector3 velocity; private bool isGrounded; void Start() { controller = GetComponent(); if (animator == null) { animator = GetComponent(); } } void Update() { // 1. เช็คว่าอยู่บนพื้นไหม isGrounded = Physics.CheckSphere(groundCheck.position, groundDistance, groundMask); if (isGrounded && velocity.y < 0) { velocity.y = -2f; } // 2. รับค่าจากปุ่ม WASD float x = Input.GetAxis("Horizontal"); float z = Input.GetAxis("Vertical"); Vector3 move = transform.right * x + transform.forward * z; // เช็คว่ากดเดินอยู่หรือไม่ bool isMoving = move.magnitude > 0.1f; // เช็คว่ากด Shift วิ่งหรือไม่ bool isSprinting = isMoving && Input.GetKey(KeyCode.LeftShift); // เลือกความเร็ว float currentSpeed = isSprinting ? runSpeed : walkSpeed; // เคลื่อนที่ controller.Move(move * currentSpeed * Time.deltaTime); // 3. การกระโดด if (Input.GetButtonDown("Jump") && isGrounded) { velocity.y = Mathf.Sqrt(jumpHeight * -2f * gravity); if (animator != null) { animator.SetTrigger("Jump"); // ใช้ Trigger "Jump" ที่คุณมี } } // แรงโน้มถ่วง velocity.y += gravity * Time.deltaTime; controller.Move(velocity * Time.deltaTime); // 4. ส่งค่าไปยัง Animator (ใช้ตัวแปรเดิมของคุณเป๊ะๆ) if (animator != null) { // คำนวณค่า Speed ส่งไป Animator: // ยืนนิ่ง = 0 | เดิน = 0.5 | วิ่ง = 1.0 float animSpeed = 0f; if (isMoving) { animSpeed = isSprinting ? 1f : 0.5f; } animator.SetFloat("Speed", animSpeed); // ส่งค่าเข้าตัวแปร Speed (Float) animator.SetBool("IsGrounded", isGrounded); // ส่งค่าเข้าตัวแปร IsGrounded (Bool) } } }