unity3d - Unity 镜像网络对象不在客户端上移动
问题描述
我正在开发网络游戏,但遇到了子弹的实例化或 NetworkSpawn 的问题。如果主机播放器/服务器“开火”,子弹就会跨过、同步并按照它应该做的方式飞行。如果客户端“开火”,子弹将被生成,但会停留在一个点上,没有任何速度。
服务器/主机触发-> 一切正常。
客户端开火 -> 子弹产生但不移动。
下面我将向您展示脚本的一部分:
public bool shootableAngle = false;
public float bulletSpeed = 6.0f;
public GameObject bulletPrefab;
public float bulletRangeTime;
private void Update()
{
if (!isLocalPlayer)
{
return;
}
if (Input.GetMouseButtonDown(0) && shootableAngle)
{
CmdFire();
}
}
[Command]
void CmdFire()
{
//Instantiate bullet
GameObject bullet = Instantiate(bulletPrefab, transform.position, transform.rotation);
//Look for crosshair child and set direction
var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction = (transform.GetChild(0).gameObject.transform.position - transform.position).normalized;
//Give some velocity
bullet.GetComponent<Rigidbody2D>().velocity = direction * bulletSpeed;
//Spawn over Network
NetworkServer.Spawn(bullet);
//Destroy after given time
Destroy(bullet, bulletRangeTime);
}
感谢你的付出!:-)
解决方案
您需要从服务器调用客户端上的函数。使用:
[ClientRpc]
RpcFireOnClient(){
//Instantiate bullet
GameObject bullet = Instantiate(bulletPrefab, transform.position,
transform.rotation);
//Look for crosshair child and set direction
var mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
Vector2 direction =
(transform.GetChild(0).gameObject.transform.position -
transform.position).normalized;
//Give some velocity
bullet.GetComponent<Rigidbody2D>().velocity = direction * bulletSpeed;
//Spawn over Network
NetworkServer.Spawn(bullet);
//Destroy after given time
Destroy(bullet, bulletRangeTime);
}
并从以下位置调用它:
[Command]
void CmdFire()
{
RpcFireOnClient();
}
我希望它有所帮助,我现在正在学习它,不知道它是否完全正确。但是试一试!
干杯