整理逻辑思路:
//【业务逻辑】这个脚本用来1.控制物体移动旋转(WASD)、 2.发射子弹(空格键)
//【程序逻辑2】
首先检测用户没有按下空格键 2.如果按下呢执行发射子弹函数 3.克隆子弹 4.让克隆的子弹往前跑
搭建场景
为子弹模板添加刚体,并且限制旋转
编写脚本:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEditor; using UnityEngine.UI; using System.IO; public class RoleControl : MonoBehaviour { //【业务逻辑】这个脚本用来控制物体移动旋转(WASD)、发射子弹(空格键) //【程序逻辑】1.首先检测用户是否按下空格键 2.如果按下就执行发射子弹的函数 // 3.发射子弹的函数:创建一个子弹 (克隆函数)4.然后让子弹往枪口前方Z轴移动 public GameObject Zidanmuban;//用来存储子弹模板物体 public GameObject ZidanBorn;//用来存储子弹的出生地空物体 public GameObject ZidanParent;//将来用于存储场景中克隆出来的子弹的父物体 public float Forcedaxiao = 10f; //--------------------------------------------- GameObject tempZidan;//用来存储克隆出来的临时子弹物体 public float Movespeed = 10f;//主角移动速度控制 public float Rotatepeed = 10f;//主角旋转速度控制 void Start() { Zidanmuban = GameObject.Find("Zidanmuban"); //从场景中查找到并存储子弹模板物体 ZidanBorn = GameObject.Find("ZidanBorn");//从场景中查找到并存储子弹出生地物体 ZidanParent = GameObject.Find("ZidanParent");//从场景中查找到并存储子弹父亲物体 } void Update() { ControlMove();//用来控制主角移动旋转 if (Input.GetKeyDown(KeyCode.Space)) { Debug.Log("用户按下空格键"); FPSShot(); } GameObject.Destroy(tempZidan, 2f);//两秒后销毁物体 } void FPSShot() { Debug.Log("用户开始发射子弹"); tempZidan = GameObject.Instantiate(Zidanmuban, ZidanBorn.transform.position, Quaternion.Euler(0, 0, 0), ZidanParent.transform);//克隆子弹 tempZidan.GetComponent<Rigidbody>().AddForce(ZidanBorn.transform.forward*Forcedaxiao, ForceMode.Impulse); tempZidan.transform.Rotate(ZidanBorn.transform.TransformDirection(new Vector3(90,0,0))); } void ControlMove()//用来控制主角移动旋转 { //获取WS\AD的数值返回-1 - 1用来移动主角物体方向 float MoveX = Input.GetAxis("Horizontal"); float MoveY = Input.GetAxis("Vertical"); this.transform.Translate(new Vector3 (MoveX, 0,MoveY)*Movespeed*Time.deltaTime); //接下来获取鼠标平移返回-1 - 1用来旋转主角物体 float RotateDir = Input.GetAxis("Mouse X"); this.transform.Rotate(new Vector3(0,1,0)* Rotatepeed*RotateDir * Time.deltaTime); } }
摄像机跟踪和脚本
这个脚本需要挂在到摄像机,里面谈到的目标物体是在场景中,主角身上加了个空物体,并且放在主角后方,这个变量需要外部给
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
// 用来控制摄像机平滑跟踪
[SerializeField]
public GameObject oneTarget;//摄像机跟踪目标点,外部赋值
public float Followspeed = 1f;
void Update()
{
if (oneTarget != null)
{
Vector3 FinllTargetPos = oneTarget.transform.TransformPoint(0, 5, -5);
this.transform.position = Vector3.Lerp(this.transform.position, FinllTargetPos, Followspeed * Time.deltaTime);
transform.LookAt(oneTarget.transform);
}
}
}