包括射击发射,人物移动,子弹销毁,摄像机平滑移动
1.建立场景,做人物(我的极其简单,想好看点,可以去下载模型),我建立的人物是由两个圆组成的人身,和一个立方体组成的
2.射击发射、人物移动、子弹销毁为一个代码中(关于代码有一些要注意,代码中Find查找中的物体名称要与自己所建场景一致,Zidanmuban和ZidanBorn位置要差不多一致,由于人物的移动,所以ZidanBorn要在任务的枪杆中;而Zidanmuban因为在人物中,运行时会被压扁,所以在人物外;ZidanParent的位置随意;这里ZidanBorn是子弹发射时产出的位置,它是一个空物体;Zidanmuban是克隆子弹的模板,是一个胶囊体,也可自行换物体,为了能看清,我将子弹模板放大以便识别;ZidanParent是暂存克隆子弹的位置,它也是一个空物体)
3.关于子弹模版,需要添加rigibody刚体,并取消use gravity也就是重力(目前来说,在此代码中子弹是并没有销毁作用)。
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);
}
}
4.关于摄像机的的平滑移动。要在人物中建立一个空物体作为摄像机的跟踪目标,找好角度(我一般将目标放置于观察对象的后上方),看向的目标是人物(所有的物体位置关系大概都在第二个图中)
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraFollow : MonoBehaviour
{
// 用来控制摄像机平滑跟踪
[SerializeField]
public GameObject oneTarget;//摄像机跟踪目标点,外部赋值
public float Followspeed = 1f;
public void Start()
{
oneTarget = GameObject.Find("CameraPoint");
}
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);
}
}
}