Untitled

 avatar
unknown
csharp
3 months ago
2.9 kB
5
Indexable
using System.Collections;
using Unity.Netcode;
using UnityEngine;

public class Shift : AbstractAbility
{
    public override int Id { get; } = GlobalResources.ShiftID;
    public override int SortOrder { get; } = 4;

    public override string Name { get; } = "<color=red>Shifter</color>";
    public override float Cooldown { get; set; } = 8f;
    public override bool OnCooldown { get; set; }

    private IAbilityInteractable InitialSwapObject;
    private IAbilityInteractable SecondSwapObject;

    private Actions input;

    private void OnEnable()
    {
        input = new Actions();
        input.Enable();
    }

    private void OnDisable()
    {
        input.Disable();
    }

    public void Activate(IAbilityInteractable first, IAbilityInteractable second)
    {
        Vector3 firstPos = first.Rigidbody.position;
        Vector3 secondPos = second.Rigidbody.position;
        print($"SWAPPING {first} ({firstPos}) AND {second} ({secondPos})");

        NetworkObjectReference aRef = new NetworkObjectReference(first.Rigidbody.GetComponent<NetworkObject>());
        NetworkObjectReference bRef = new NetworkObjectReference(second.Rigidbody.GetComponent<NetworkObject>());

        PerformSwapServerRpc(aRef, bRef);

        first?.OnSwapped(second);
        second?.OnSwapped(first);

        InitialSwapObject = null;
        SecondSwapObject = null;
    }

    private IEnumerator ReenableCollisionAfterDelay(Collider a, Collider b)
    {
        yield return new WaitForSeconds(1f); // Let physics settle
        Physics.IgnoreCollision(a, b, false);
    }

    [ServerRpc(RequireOwnership = false)]
    public void PerformSwapServerRpc(NetworkObjectReference aRef, NetworkObjectReference bRef)
    {
        print("IN1");
        if (aRef.TryGet(out NetworkObject aObj) && bRef.TryGet(out NetworkObject bObj))
        {
            print("IN2");
            Rigidbody aRb = aObj.GetComponent<Rigidbody>();
            Rigidbody bRb = bObj.GetComponent<Rigidbody>();

            Vector3 aPos = aRb.position;
            Vector3 bPos = bRb.position;

            aRb.MovePosition(bPos);
            bRb.MovePosition(aPos);
        }
    }

    public override void Activate(IAbilityInteractable other)
    {
        if (OnCooldown) return;
        if (InitialSwapObject == null)
        {
            InitialSwapObject = other;
            print("INITIAL: " + InitialSwapObject);
            return;
        }

        if (SecondSwapObject == null && other != InitialSwapObject)
        {
            SecondSwapObject = other;
            print("SECOND: " + SecondSwapObject);
        }

        if (InitialSwapObject != null && SecondSwapObject != null)
        {
            Activate(InitialSwapObject, SecondSwapObject);
        }
    }
}
Editor is loading...
Leave a Comment