Unity脚步之NetworkBehaviour下前进、后退、左右转向的简单移动
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.Networking; public class PlayerCtrl : NetworkBehaviour//将默认的MonoBehavior替换为NetworkBehavior { //定义两个方向轴 private float horizontal = 0.0f; private float vertical = 0.0f; //子弹预制体 public GameObject bulletPrefab; //子弹初始速度 public int bulletSpeed = 25; //子弹生成器位置 public Transform bulletSpawn; /*不需要Start方法了 // Use this for initialization void Start () { } */ // Update is called once per frame void Update() { //如果不是本地角色就不往下执行 if (!isLocalPlayer) { return; } horizontal = Input.GetAxis("Horizontal"); vertical = Input.GetAxis("Vertical"); //旋转角色,按照Y轴,每次旋转120° transform.Rotate(Vector3.up * horizontal * 120 * Time.deltaTime); //移动角色,每次移动3米 transform.Translate(Vector3.forward * vertical * 3 * Time.deltaTime); //开火,发射子弹 if (Input.GetKeyDown(KeyCode.Space)) { Fire(); } } //这个方法只会在本地客户端调用 public override void OnStartLocalPlayer() { //用<网格渲染器>更改角色材质颜色 GetComponent<MeshRenderer>().material.color = Color.yellow; } //开火 void Fire() { //子弹预制体实例化 GameObject bullet = Instantiate(bulletPrefab, bulletSpawn.position, bulletSpawn.rotation) as GameObject; //给子弹刚体初始速度赋值 bullet.GetComponent<Rigidbody>().velocity = bullet.transform.forward * bulletSpeed; //2秒之后销毁子弹 Destroy(bullet, 2); } }