RPC в photon не отправляет данные по сети

#c# #visual-studio #unity3d #photon

Вопрос:

Ммм, значит, я пытался использовать фотонные RPC, но, похоже, он не отправляет информацию по сети?

В настоящее время, когда игрок снимает, это отображается только на его компьютере, но никто другой, играющий в той же комнате, не может этого видеть

PlayerShoot.cs

 using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Photon.Pun;
public class playerShoot : MonoBehaviourPunCallbacks
{
    public Transform shootPoint;
    public LineRenderer gunLine;
    public float range = 30f;
    RaycastHit hit;
    Ray ray;
    public PhotonView photonview;
    // Start is called before the first frame update
    void Start()
    {
        gunLine = GetComponent<LineRenderer>();
        photonview = PhotonView.Get(this);
        
    }

    // Update is called once per frame
    void Update()
    {
        if (!photonView.IsMine)
            return;
        photonview.RPC("shoot",RpcTarget.All);
        //shoot();
    }
    [PunRPC]
    public void shoot()
    {
        if (!photonView.IsMine)// still need to call this coz the one in update doesn't seem to work?
            return;

        if (Input.GetButton("Fire1"))
        {
            gunLine.enabled = true;
            gunLine.SetPosition(0, shootPoint.position);

            ray.origin = shootPoint.position;
            ray.direction = transform.forward;
            if (Physics.Raycast(ray, out hit, range))
            {

                //Debug.DrawRay(transform.position, transform.TransformDirection(Vector3.forward) * hit.distance, Color.red);
                Debug.Log(hit.point);
                gunLine.SetPosition(1, hit.point);
            }
            else
            {
                gunLine.SetPosition(1, ray.origin   ray.direction * range);
            }

        }
        else
            gunLine.enabled = false;
    }
}

 

Видео, демонстрирующее проблему:

https://youtu.be/RMtCDTCyQk0

Ответ №1:

На всех приемниках if (!photonView.IsMine) сообщение будет ложным, так что там ничего не произойдет.

Вы также не хотите получать ввод с клавиатуры/мыши от приемников, а скорее от локального устройства! Кроме того, радиопередача должна выполняться только на локальном устройстве.

Затем, как только вы соберете все необходимые значения, вы передадите только их методу съемки и всем остальным.

Это должно скорее выглядеть, например, как

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

    // Gather all this information only on the local device
    var firePressed = Input.GetButton("Fire1");
    var position0 = shootPoint.position;
    var position1 = Vector3.zero;

    if (firePressed)
    {
        ray.origin = shootPoint.position;
        ray.direction = transform.forward;
        if (Physics.Raycast(ray, out hit, range))
        {
            Debug.Log(hit.point);
            position1 = hit.point;
        }
        else
        {
            position1 = ray.origin   ray.direction * range;
        }
    }

    // Then forward it to the actual shoot and to all other clients
    photonview.RPC("shoot",RpcTarget.All, firePressed, position0, position1);
}

[PunRPC]
public void shoot(bool firePressed, Vector3 position0, Vector3 position1)
{
    // Now having all required values every device can reproduce the desired behavior
    gunLine.enabled = firePressed;

    if(firePressed)
    {
        gunLine.SetPosition(0, position0);
        gunLine.SetPosition(1, position1);
    }  
}
 

Однако обратите внимание, что отправлять вызов RPC в каждом кадре довольно плохо. Вы могли бы подумать о том, чтобы ваша съемка происходила через определенные промежутки времени (по крайней мере, для удаленных клиентов).