using Photon.Pun;
using TMPro;
using UnityEngine;

public class PlayerController : MonoBehaviourPun
{
    public float speed = 5f;
    public TMP_Text usernameText;

    private Transform mainCameraTransform;

    private void Start()
    {
        mainCameraTransform = Camera.main.transform;
        usernameText.text = photonView.Owner.NickName;

        var renderer = GetComponentInChildren<Renderer>();
        if (photonView.IsMine)
            renderer.material.color = Color.blue;
        else
            renderer.material.color = Color.red;

        if (!photonView.IsMine)
            return;
    }

    private void Update()
    {
        if (!photonView.IsMine)
            return;

        float h = Input.GetAxis("Horizontal");
        float v = Input.GetAxis("Vertical");
        Vector3 movement = new Vector3(h, 0f, v) * speed * Time.deltaTime;
        transform.Translate(movement, Space.World);

        Vector3 pos = transform.position;
        pos.x = Mathf.Clamp(pos.x, -10f, 10f);
        pos.z = Mathf.Clamp(pos.z, -10f, 10f);
        transform.position = pos;
    }

    private void LateUpdate()
    {
        usernameText.transform.parent.LookAt(mainCameraTransform);
    }
}
