using UnityEngine;
using System.Collections.Generic;
using Unity.Netcode;
using UnityEngine.AI;
public class PlayerController : NetworkBehaviour {
[Header("Movement Settings")]
[SerializeField] private float moveSpeed = 5f;
[SerializeField] private float jumpForce = 10f;
[SerializeField] private float sprintMultiplier = 1.5f;
[SerializeField] private LayerMask groundLayer;
[Header("Network Variables")]
private NetworkVariable<Vector3> networkPosition = new NetworkVariable<Vector3>();
private NetworkVariable<float> networkRotation = new NetworkVariable<float>();
[Header("Components")]
private Rigidbody rb;
private Animator animator;
private CharacterController controller;
private bool isGrounded;
private Vector3 moveDirection;
private float currentSpeed;
public override void OnNetworkSpawn() {
rb = GetComponent<Rigidbody>();
animator = GetComponent<Animator>();
controller = GetComponent<CharacterController>();
InitializePlayer();
}
void Update() {
if (!IsOwner) return;
HandleInput();
CheckGrounded();
MovePlayer();
UpdateAnimations();
if (IsServer) {
networkPosition.Value = transform.position;
networkRotation.Value = transform.eulerAngles.y;
}
}
private void HandleInput() {
float horizontal = Input.GetAxis("Horizontal");
float vertical = Input.GetAxis("Vertical");
bool isSprinting = Input.GetKey(KeyCode.LeftShift);
moveDirection = new Vector3(horizontal, 0, vertical).normalized;
moveDirection = transform.TransformDirection(moveDirection);
currentSpeed = isSprinting ? moveSpeed * sprintMultiplier : moveSpeed;
if (Input.GetKeyDown(KeyCode.Space) && isGrounded) {
Jump();
}
if (Input.GetKeyDown(KeyCode.F)) {
InteractServerRpc();
}
}
private void MovePlayer() {
Vector3 velocity = moveDirection * currentSpeed;
velocity.y = rb.velocity.y;
rb.velocity = velocity;
if (moveDirection.magnitude > 0.1f) {
Quaternion targetRotation = Quaternion.LookRotation(moveDirection);
transform.rotation = Quaternion.Lerp(transform.rotation, targetRotation, Time.deltaTime * 10f);
}
}
private void Jump() {
rb.AddForce(Vector3.up * jumpForce, ForceMode.Impulse);
JumpServerRpc();
animator.SetTrigger("Jump");
}
private void CheckGrounded() {
Ray ray = new Ray(transform.position + Vector3.up * 0.1f, Vector3.down);
isGrounded = Physics.Raycast(ray, 1.2f, groundLayer);
animator.SetBool("IsGrounded", isGrounded);
}
private void UpdateAnimations() {
animator.SetFloat("Speed", rb.velocity.magnitude);
animator.SetBool("IsSprinting", currentSpeed > moveSpeed);
}
[ServerRpc]
private void JumpServerRpc() {
JumpClientRpc();
}
[ClientRpc]
private void JumpClientRpc() {
PlayJumpEffect();
AudioSource.PlayClipAtPoint(jumpSound, transform.position);
}
[ServerRpc]
private void InteractServerRpc() {
// Handle interaction logic
Debug.Log("Player interacted: " + gameObject.name);
}
}