41 lines
1.3 KiB
C#
41 lines
1.3 KiB
C#
using UnityEngine;
|
|
|
|
public class PlayerController : MonoBehaviour
|
|
{
|
|
public Joystick joystick; // Kéo Fixed Joystick ở Canvas vào đây
|
|
public float moveSpeed = 2f;
|
|
public Animator animator; // Kéo Animator của nhân vật vào đây
|
|
|
|
void Update()
|
|
{
|
|
if (joystick == null)
|
|
{
|
|
Debug.LogWarning("Joystick is not assigned in PlayerController!");
|
|
return;
|
|
}
|
|
|
|
// Lấy input từ Joystick
|
|
float horizontal = joystick.Horizontal;
|
|
float vertical = joystick.Vertical;
|
|
|
|
// Di chuyển object theo trục X và Z
|
|
Vector3 direction = new Vector3(horizontal, 0, vertical).normalized;
|
|
float currentSpeed = direction.magnitude * moveSpeed;
|
|
|
|
transform.Translate(direction * moveSpeed * Time.deltaTime, Space.World);
|
|
|
|
// Xoay object mượt mà theo hướng di chuyển
|
|
if (direction != Vector3.zero)
|
|
{
|
|
Quaternion targetRotation = Quaternion.LookRotation(direction);
|
|
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, 15f * Time.deltaTime);
|
|
}
|
|
|
|
// Cập nhật Animator
|
|
if (animator != null)
|
|
{
|
|
// Giả sử Animator có parameter "Speed" kiểu Float
|
|
animator.SetFloat("Speed", currentSpeed);
|
|
}
|
|
}
|
|
} |