c#Unity - 与对象交互的多人游戏

时间:2018-03-27 22:06:44

标签: c# unity3d networking game-engine multiplayer

  using UnityEngine;
using UnityEngine.Networking;

public class Interactable : NetworkBehaviour {

    public float radius = 2f;
    bool isFocus = false;
    Transform player;
    bool hasInteracted = false;
    public Transform interactionPoint;



    public virtual void Interact()
    {
        // This method is meant to be overwritten
        Debug.Log("Interacting with " + transform.name);
    }

    private void Update()
    {
        if (isFocus && !hasInteracted)
        {

            float distance = Vector3.Distance(player.position, interactionPoint.position);

             if(distance <= radius)
            {
                Interact();
                hasInteracted = true;

            }


        }


    }

    public void onFocused(Transform Player)
    {
        isFocus = true;
        player = Player;
    }

    public void onDeFocused()
    {
        isFocus = false;
        player = null;
        hasInteracted = false;


    }
    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.yellow;
        Gizmos.DrawWireSphere(transform.position, radius);

    }

}

这是为了覆盖的交互。

 using System.Collections;
    using System.Collections.Generic;
    using UnityEngine;
    using UnityEngine.Networking;


public class SphereBehaviour : Interactable {

    public float countdown = 1;
    public float timeLeft = 5f;



    public override void Interact()
    {
        Debug.Log("Interacting with the Sphere object");
        StartCoroutine(StartCountdown());


    }

    public IEnumerator StartCountdown() // Countdown from 5
    {
        countdown = timeLeft;
        while (countdown > 0)
        {
            yield return new WaitForSeconds(1.0f);
            countdown--;
        }

    }

问题是这不是网络化的,我无法想到这样做的逻辑。界面不起作用或任何事情。是否有任何可能的解决方案并不需要改变一切?

我只是想把Brackeys的一套youtube教程变成多人游戏。

1 个答案:

答案 0 :(得分:0)

我假设您正在为某些UI元素使用公共“倒计时”变量。

  1. 如果你希望每个玩家在他们自己触摸这个球体时看到他们自己的倒计时,这应该可以正常工作。

  2. 如果有人触摸球体应该触发每个人的倒计时,那么必须采取不同的方式。您希望主机/服务器跟踪玩家和球体之间的交互,然后触发客户端的倒计时协程。

  3. 我个人不建议在任何情况下使用#1,因为冲突/交互应该在服务器端完成。