Skip to main content

加了子弹

让角色可以射出子弹

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

public class Move : NetworkBehaviour
{
public GameObject bulletPrefab; //子弹
public Transform BulletSpawn; //子弹生成的位置

// Update is called once per frame
void Update()
{
if (isLocalPlayer == false)
{
return;
}

float h = Input.GetAxis("Horizontal");
float v = Input.GetAxis("Vertical");

transform.Rotate(Vector3.up * h *120 * Time.deltaTime);
transform.Translate(Vector3.forward * v * 3 * Time.deltaTime);

//生成子弹
if(Input.GetKeyDown(KeyCode.Space))
{
Fire();
}


}

/// <summary>
/// 重写父方法,这个方法只会在本地角色那里调用
/// </summary>
public override void OnStartLocalPlayer()
{
GetComponent<MeshRenderer>().material.color = Color.blue;
// base.OnStartLocalPlayer();
}

public void Fire()
{
GameObject bullet = Instantiate(bulletPrefab, BulletSpawn.position, BulletSpawn.rotation) as GameObject;
bullet.GetComponent<Rigidbody>().velocity = bullet.transform.up * 10;
Destroy(bullet,2);
}
}

上面的代码的问题是:多客户端看不到子弹。

  1. 如果要看到子弹要给子弹加上NetworkIdcntity
  2. 并把子弹的预制体添加到 NetworkManagerRegisterd Spawnable Prefabs上面 。
  3. 并要修改Fire函数,让子弹在server端生成。做法如下
  4. 子弹身上加NetworkTransform
    • 选择 同步刚体组件: Transform Sync mod Sync Rigidbody 3D
    • 同步次数选择0 :Network Send Rate 设置为 0