Untitled

mail@pastecode.io avatar
unknown
plain_text
2 months ago
10 kB
6
Indexable
Never
using System.Collections;
using UnityEngine;
using UnityEngine.UI;
using Alteruna;
using System.Runtime.CompilerServices;


public class MultiplayerHealth : AttributesSync
{
    //private Text playerHealthText;
    public int startingHealth = 100;
    public int currentHealth;
    public float invulnerabilityTime = 1f;
    public float timeAfterWeLastTookDamage = 1f;
    //private Slider healthSlider;
    //private Image damageImage;
    public AudioClip deathClip;
    // private Image healthFillImage;
    public GameObject HUDCanvas;
    Animator anim;
    AudioSource playerAudio;
    MultiplayerMovement multiplayerMovement;
    MultiplayerShooting multiplayerShooting;
    public bool isDead;
    bool damaged;
    float timer;
    private Spawner _spawner;
    [SerializeField] private int indexToSpawn = 5;
    public User Me { get; }
    public string Name { get; }
    SkinnedMeshRenderer myRenderer;
    Color rimColor;
    float rimPower;
    Alteruna.Avatar _avatar;
    public CameraFollowMultiplayer cameraFollow;
    Transform playerTransform;
    private CanvasManager canvasManager;
    // Distance within which a player can revive the dead player
    public float revivalDistance = 0.5f;
    // Health restored per second during revival
    public int revivalHealthPerSecond = 20;

    public static MultiplayerHealth Instance { get; private set; }

    void Awake()
    {
        anim = GetComponent<Animator>();
        playerAudio = GetComponent<AudioSource>();
        multiplayerMovement = GetComponent<MultiplayerMovement>();
        multiplayerShooting = GetComponentInChildren<MultiplayerShooting>();

        currentHealth = startingHealth;


        SkinnedMeshRenderer[] meshRenderers = GetComponentsInChildren<SkinnedMeshRenderer>();
        foreach (SkinnedMeshRenderer meshRenderer in meshRenderers)
        {
            if (meshRenderer.gameObject.name == "Player")
            {
                myRenderer = meshRenderer;
                break;
            }
        }
        _spawner = GameObject.FindGameObjectWithTag("NetworkManager").GetComponent<Spawner>();
        GameObject HUDCanvas = _spawner.Spawn(indexToSpawn);

    }

    private void OnRoomJoined(Multiplayer multiplayer, Room room, User user)
    {
        playerTransform = Multiplayer.GetAvatar().transform;
        NetworkWaveManager.Instance.isHost = user.IsHost;
        _avatar = GetComponent<Alteruna.Avatar>();
        currentHealth = startingHealth;
        // Check if CanvasManager.Instance is not null before accessing its properties
        if (CanvasManager.Instance != null)
        {
            // CanvasManager.Instance.UpdatePlayerHealth(currentHealth);
            //CanvasManager.Instance.healthSlider.value = startingHealth;
            //CanvasManager.Instance.healthFillImage.color = CanvasManager.Instance.maxHealthColor;
        }
        else
        {
            Debug.LogError("CanvasManager.Instance is null!");
        }
        // GetComponent<Camera>().enabled = _avatar.IsMe;


    }


    void Start()
    {
        rimColor = myRenderer.materials[0].GetColor("_RimColor");
        rimPower = myRenderer.materials[0].GetFloat("_RimPower");
        _avatar = GetComponent<Alteruna.Avatar>();
        playerTransform = Multiplayer.GetAvatar().transform;
        if (_avatar.IsOwner)
        {
        

               Camera.main.enabled = _avatar.IsOwner;
            //  Camera.main.GetComponent<CameraFollowMultiplayer>().SetTarget(gameObject.transform);
        }
    }

    void Update()
    {
        if (!_avatar.IsOwner)
            return;
        {
            if (damaged)
            {
                // canvasManager.damageImage.color = flashColour;
                CanvasManager.Instance.FlashDamageImage();

            }
            else
            {
                CanvasManager.Instance.ClearColour();

                //canvasManager.damageImage.color = Color.Lerp(canvasManager.damageImage.color, Color.clear, flashSpeed * Time.deltaTime);
            }
        }
        if (isDead)
        {
            // Check for nearby players and initiate revival
            CheckForRevival();
        }

        timer += Time.deltaTime;
        damaged = false;

        timer += Time.deltaTime;
        damaged = false;
    }

    [SynchronizableMethod]
    public int GetCurrentHealth()
    {
        return currentHealth;
    }

    [SynchronizableMethod]
    void OnCurrentHealthChanged(int oldValue, int newValue)
    {
        // Update health UI elements here
        if (_avatar.IsOwner)
    {
            CanvasManager.Instance.UpdatePlayerHealth(newValue);
        }
        // canvasManager.playerHealthText.text = newValue.ToString();
        //canvasManager.healthSlider.value = newValue;
        // Additional UI updates...
    }

    [SynchronizableMethod]
    void OnDamagedChanged(bool oldValue, bool newValue)
    {
        if (_avatar.IsOwner)
        {
            if (newValue)
        {
            StartCoroutine("IsHit");
        }
        }
    }

    [SynchronizableMethod]
    public void TakeDamage(int amount)
    {
        if (_avatar.IsOwner && timer >= invulnerabilityTime)
        {
            BroadcastRemoteMethod(nameof(TakeDamageSync), amount);
        }
    }

    //[ClientRpc]
    [SynchronizableMethod]
    public void TakeDamageSync(int amount)
    {
        if (_avatar.IsOwner)
        {
            StopCoroutine("IsHit");
            StartCoroutine("IsHit");

            damaged = true;
            currentHealth -= amount;
            int health = Mathf.Max(currentHealth, 0);

            // Use CanvasManager to update the UI
            CanvasManager.Instance.UpdatePlayerHealth(health);

            if (currentHealth > startingHealth)
            {
                currentHealth = startingHealth;
            }

            CanvasManager.Instance.healthSlider.value = currentHealth;
            CanvasManager.Instance.healthFillImage.color = CanvasManager.Instance.maxHealthColor;

            if (currentHealth <= startingHealth * 0.3)
            {
                CanvasManager.Instance.healthFillImage.color = CanvasManager.Instance.minHealthColor;
            }

            timer = 0;
            playerAudio.Play();

            if (currentHealth <= 0 && !isDead)
            {
                Deathbegins();
            }
        }
    }

    IEnumerator IsHit()
    {
        Color newColor = new Color(10, 0, 0, 0);
        float newPower = 0.5f;

        myRenderer.materials[0].SetColor("_RimColor", newColor);
        myRenderer.materials[0].SetFloat("_RimPower", newPower);

        float time = 0.25f;
        float elapsedTime = 0;
        while (elapsedTime < time)
        {
            newColor = Color.Lerp(newColor, rimColor, elapsedTime / time);
            myRenderer.materials[0].SetColor("_RimColor", newColor);
            newPower = Mathf.Lerp(newPower, rimPower, elapsedTime / time);
            myRenderer.materials[0].SetFloat("_RimPower", newPower);
            elapsedTime += Time.deltaTime;
            yield return null;
        }
        myRenderer.materials[0].SetColor("_RimColor", rimColor);
        myRenderer.materials[0].SetFloat("_RimPower", rimPower);
    }


    [SynchronizableMethod]
    public void AddHealth(int amount)
    {
        if (_avatar.IsOwner)
        {
            currentHealth += amount;

        if (currentHealth > startingHealth)
        {
            currentHealth = startingHealth;
        }

        // Use CanvasManager to update the UI
        CanvasManager.Instance.UpdatePlayerHealth(currentHealth);

        if (currentHealth <= startingHealth * 0.3)
        {
            CanvasManager.Instance.healthFillImage.color = CanvasManager.Instance.minHealthColor;
        }
        }
    }

    // [ServerCallback]
    void Deathbegins()
    {
        isDead = true;
        BroadcastRemoteMethod("Death");
        //Death();
    }

    // [ClientRpc]
    [SynchronizableMethod]
    void Death()
    {
        multiplayerShooting.DisableEffects();
        anim.SetTrigger("Die");
        playerAudio.clip = deathClip;
        playerAudio.Play();
        multiplayerMovement.enabled = false;
        multiplayerShooting.enabled = false;
    }

    void CheckForRevival()
    {
        // Find all players in the scene
        MultiplayerHealth[] players = FindObjectsOfType<MultiplayerHealth>();

        foreach (MultiplayerHealth player in players)
        {
            if (player != this && !player.isDead)
            {
                float distance = Vector3.Distance(transform.position, player.transform.position);

                if (distance < revivalDistance)
                {
                    // Revive the dead player
                    RevivePlayer();
                    break;
                }
            }
        }
    }

    void RevivePlayer()
    {
        // Add health gradually during the revival process
        StartCoroutine(RevivalProcess());
    }

    IEnumerator RevivalProcess()
    {
        while (currentHealth < startingHealth)
        {
            AddHealth(revivalHealthPerSecond);

            // Adjust the delay based on your needs
            yield return new WaitForSeconds(1f);
        }

        // Ensure health is set to the maximum after revival
        currentHealth = startingHealth;
        CanvasManager.Instance.UpdatePlayerHealth(currentHealth);

        // Reset flags and perform any additional actions upon reaching full health
        // isDead = false;


        if (currentHealth == startingHealth)
        {
            isDead = false;
            BroadcastRemoteMethod("Revive");
        }
    }

    [SynchronizableMethod]
    void Revive()
    {
        multiplayerMovement.enabled = true;
        multiplayerShooting.enabled = true;
        anim.Rebind();
        anim.Update(0f);
    }
}
Leave a Comment