[英]Client disconnect when shooting in Unity (Mirror)
I am making an online multiplayer game in Unity with Mirror Networking.我正在使用 Mirror Networking 在 Unity 中制作在线多人游戏。 In this script I am trying to shoot a bullet by calling, from the client, a command on the server ( CmdFire() ) that instantiate a projectile from a shot position using the rotation of the player camera.在这个脚本中,我试图通过从客户端调用服务器上的命令( CmdFire() )来发射子弹,该命令使用玩家相机的旋转从 position 实例化射弹。 The issue that I have is that when I try to shoot a bullet from the client machine he disconnect where if the host tries to shoot the projectile is not visible to the client.我遇到的问题是,当我尝试从客户端机器射击子弹时,他断开连接,如果主机尝试射击弹丸,客户端看不到。 This is my code:这是我的代码:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Mirror;
public class Shooter : NetworkBehaviour
{
public GameObject projectilePrefab;
public Transform shootPos;
public Camera playerCamera;
bool canShoot = true;
public AudioSource shotSound;
[Command]
void CmdFire()
{
GameObject projectile = Instantiate(projectilePrefab, shootPos.position, playerCamera.transform.rotation);
NetworkServer.Spawn(projectile);
}
// Update is called once per frame
void Update()
{
if (!hasAuthority) return;
if (Input.GetButton("Fire1"))
{
if (canShoot)
{
canShoot = false;
GenerateRayCast();
CmdFire();
StartCoroutine(FireDelay());
shotSound.Play();
}
}
}
Transform GenerateRayCast()
{
playerCamera = transform.Find("CameraMountPosition").Find("Camera").GetComponent<Camera>();
Ray ray = new Ray(shootPos.transform.position, playerCamera.transform.forward * 500);
Debug.DrawRay(shootPos.transform.position, playerCamera.transform.forward * 500, Color.red, 2f);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Debug.LogError("SERVER: Player shot: " + hit.collider.name);
if (hit.collider.CompareTag("Player"))
{
//deal damage
}
}
return hit.transform;
}
// Cooldown before shooting again
IEnumerator FireDelay()
{
yield return new WaitForSeconds(2);
canShoot = true;
}
}
I ended up changing the whole way the player shoots projectiles.我最终改变了玩家发射弹丸的整个方式。
First of all I avoided using the player camera to understand the direction for spawning the projectile and I used another gameObject that was basically having the same behaviour of the camera but that was placed IN the player prefab.首先,我避免使用玩家相机来了解生成弹丸的方向,并且我使用了另一个游戏对象,它基本上具有与相机相同的行为,但它被放置在玩家预制件中。
The other thing I did was using non-network identity projectiles.我做的另一件事是使用非网络身份射弹。 So i spawned the projectile both in the Client and in the Server.所以我在客户端和服务器中都生成了弹丸。
void Fire()
{
if (!base.hasAuthority) return;
//if is client spawn on here
if (!base.isServer)
{
Projectile p = Instantiate(projectilePrefab, shootPos.position, shootPos.rotation);
}
//spawn on the server
CmdFire(shootPos.position, shootPos.rotation);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.