Episode 02
Gun System——武器系统
Player
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(PlayerController))]
[RequireComponent(typeof(GunController))]
public class Player : MonoBehaviour
{
public float moveSpeed = 5;
Camera viewCamera;
PlayerController controller;
GunController gunController;
void Start()
{
controller = GetComponent<PlayerController>();
gunController = GetComponent<GunController>();
viewCamera = Camera.main;
}
void Update()
{
//实现Player移动
Vector3 moveInput = new Vector3(Input.GetAxisRaw("Horizontal"), 0, Input.GetAxisRaw("Vertical"));
Vector3 moveVelocity = moveInput.normalized * moveSpeed;
controller.Move(moveVelocity);
//实现Player朝向鼠标位置
Ray ray = viewCamera.ScreenPointToRay(Input.mousePosition);
Plane groundPlane = new Plane(Vector3.up, Vector3.zero);
float rayDistance;
if (groundPlane.Raycast(ray, out rayDistance))
{
Vector3 point = ray.GetPoint(rayDistance);
//Debug.DrawLine(ray.origin, point, Color.red);
//Debug.DrawRay(ray.origin,ray.direction * 100,Color.red);
controller.LookAt(point);
}
//实现Gun射击
if (Input.GetMouseButton(0))
{
gunController.Shoot();
}
}
}
[RequireComponent(typeof(需要依赖的Script))] :把一个Script绑定到GameObject上时会同时把需要依赖的脚本也一起绑定上去,优点:1.减少操作,当绑定需要的脚本的时候其所依赖的脚本也一起绑定;2.可以避免因遗漏绑定其他脚本而出错。
GetComponent
Gun
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Gun : MonoBehaviour
{
public Transform muzzle;
public Projectile projectile;
public float msBetweenShots = 100;
public float muzzleVelocity = 35;
float nextShotTime;
//Shoot方法实例化Projectil
public void Shoot()
{
if (Time.time > nextShotTime)
{
nextShotTime = Time.time + msBetweenShots / 1000;
Projectile newProjectile = Instantiate(projectile, muzzle.position, muzzle.rotation) as Projectile;
newProjectile.SetSpeed(muzzleVelocity);
}
}
}
msBetweenShots:两次射击的间隔时间(毫秒)
muzzleVelocity:子弹移动的速度,muzzleVeloc传给Projectile的SetSpeed设置
GunController
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GunController : MonoBehaviour
{
public Transform weaponHold;
public Gun startingGun;
Gun equippedGun;
void Start()
{
if (startingGun != null)
{
EquipGun(startingGun);
}
}
//实例化Gun
private void EquipGun(Gun gunToEquip)
{
if (equippedGun != null)
{
Destroy(equippedGun.gameObject);
}
equippedGun = Instantiate(gunToEquip, weaponHold.position ,weaponHold.rotation) as Gun;
equippedGun.transform.parent = weaponHold;
}
//调用Gun的Shoot方法
public void Shoot()
{
if (equippedGun != null)
{
equippedGun.Shoot();
}
}
}
Projectile
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Projectile : MonoBehaviour
{
float speed = 10;
public void SetSpeed(float newSpeed)
{
speed = newSpeed;
}
void Update()
{
//Projectile移动
transform.Translate(Vector3.forward * Time.deltaTime * speed);
}
}
Transform.Translate():移动,可以传入两个变量,前一个变量是物体的移动速度,这里的速度是一个矢量,既包含大小写包含方向,后一个变量是相对坐标系,这里的相对坐标系有两个值,一个是世界坐标,一个是自身坐标,如果第一个坐标不填写的话,默认为自身坐标系。
拓展: