[入门教程]Blender+Unity全流程做一个完整的游戏
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 控制角色行为,包括基础旋转,移动,状态机动画播放,跳跃,和开火
/// </summary>
public class PlayerController : MonoBehaviour
{
//基础移动变量定义
public float walkSpeed = 2;
public float runSpeed = 6;
//跳跃行为变量定义
public float gravity = -12;
public float jumpHeight = 1;
float velocityY;
//获取其他组件
public GameObject LaserPrefab;
public Transform firePosition;
private Animator animator;
private CharacterController characterController;
Transform cameraT;
void Start()
{
//初始化组件
characterController = GetComponent<CharacterController>();
animator = GetComponentInChildren<Animator>();
cameraT = Camera.main.transform;
}
// Update is called once per frame
void FixedUpdate()
{
//读取虚拟轴,构建虚拟二维方向向量
Vector2 input = new Vector2(Input.GetAxis("Horizontal"), Input.GetAxis("Vertical"));
Vector2 inputDir = input.normalized;
//当输入不为零时,根据方向向量旋转角色
if (inputDir != Vector2.zero)
{
//通过三角函数把输入转为旋转角度,弧度转角度,在y方向上旋转,并加上鼠标转动的角度
transform.eulerAngles = Vector3.up * (Mathf.Atan2(inputDir.x, inputDir.y) * Mathf.Rad2Deg + cameraT.eulerAngles.y);
}
bool running = Input.GetKey(KeyCode.LeftShift);
//检测跑步状态,给速度加上向量乘数
float speed = ((running ? runSpeed : walkSpeed)) * inputDir.magnitude;
//模拟重力影响,给角色加上一个向下的速度
velocityY += Time.fixedDeltaTime * gravity;
//合并向前的速度和向下受重力影响的速度
Vector3 velocity = transform.forward * speed + Vector3.up * velocityY;
//按合并速度移动角色
characterController.Move(velocity * Time.fixedDeltaTime);
//检测角色是否触地,如果触地,把垂直方向上的速度清零
if (characterController.isGrounded)
{
velocityY = 0;
}
//跳跃函数
if (Input.GetKey(KeyCode.Space))
{
Jump();
}
//开火函数
if (Input.GetMouseButton(0))
{
Fire();
}
//控制动画播放
float animationSpeedPercent = ((running) ? 1 : .5f) * inputDir.magnitude;
animator.SetFloat("SpeedPercent", animationSpeedPercent);
}
//根据重力公式,给角色一个向上的速度模拟跳跃
void Jump()
{
//判断角色是否触地
if (characterController.isGrounded)
{
//重力公式,v^2=2gh
float jumpVelocity = Mathf.Sqrt(-2 * gravity * jumpHeight);
velocityY = jumpVelocity;
}
}
//在头部位置生成激光
void Fire()
{
Instantiate(LaserPrefab, firePosition.position, firePosition.rotation);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 控制第三人称摄像机
/// </summary>
public class ThirdPersonCamera : MonoBehaviour
{
//定义公共变量
public float mouseSensitivity = 10;
public Transform target;
public float offset;
public Vector2 pitchMinMax = new Vector2(-40, 85);
public bool lockCursor;
//定义偏航控制摄像机水平移动,俯仰角控制摄像机上下移动
float yaw = 0;
float pitch = 0;
private void Start()
{
//隐藏鼠标
if (lockCursor)
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = false;
}
}
void Update()
{
//把鼠标横向移动传给偏航,纵向移动传给俯仰角
yaw += Input.GetAxis("Mouse X") * mouseSensitivity;
pitch -= Input.GetAxis("Mouse Y") * mouseSensitivity;
//限制俯仰角最大最小范围
pitch = Mathf.Clamp(pitch, pitchMinMax.x, pitchMinMax.y);
//构建模拟向量控制摄像机旋转
Vector3 targeteRotation = new Vector3(pitch, yaw);
//旋转摄像机
transform.eulerAngles = targeteRotation;
//控制摄像机向后偏移目标
transform.position = target.position - transform.forward * offset;
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEditor.Rendering;
using UnityEngine;
/// <summary>
/// 控制敌人行为,自动索敌,遇袭后播放爆炸动画
/// </summary>
public class EnemyBehaviour : MonoBehaviour
{
//定义外部变量
public float enemySpeed = 5f;
public float deathDistance = 0.8f;
public float respondDistance = 200;
public GameObject explosionPrefab;
//获取玩家目标
GameObject player;
float distance;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player");
}
void Update()
{
//计算敌人和玩家距离
distance = Vector3.Distance(player.transform.position, transform.position);
//如果距离小于索敌距离,敌人转向玩家,并朝玩家移动
if (distance < respondDistance)
{
transform.LookAt(player.transform);
transform.Translate(Vector3.forward * enemySpeed * Time.deltaTime);
}
//如果与玩家距离过小,游戏结束
if (distance < deathDistance)
{
Time.timeScale = 0;
}
}
//被激光集中后,生成爆炸预制件,总敌人数减一,玩家得分加一
private void OnTriggerEnter(Collider other)
{
//判断击中物体标签是否为激光
if (other.tag == "Laser")
{
//播放爆炸动画
Instantiate(explosionPrefab, transform.position + new Vector3(0, 1, 0), transform.rotation);
//摧毁敌人
Destroy(gameObject);
//敌人数减一
EnemyGenerator.enemyCount--;
//玩家得分加一
EnemyGenerator.point++;
}
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 定义激光行为
/// </summary>
public class LaserBehaviour : MonoBehaviour
{
//定义外部变量激光飞行速度
public float laserSpeed = 50f;
void Start()
{
//激光生成后10秒销毁
Destroy(gameObject, 10f);
//获取子集中的刚体组件,与敌人进行碰撞检测
GetComponentInChildren<Rigidbody>().velocity = transform.forward * laserSpeed;
}
private void OnTriggerEnter(Collider other)
{
//击中物体后摧毁激光
Destroy(gameObject);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 控制爆炸动画
/// </summary>
public class ExplosionBehaviour : MonoBehaviour
{
void Start()
{
//生成后1秒即销毁
Destroy(gameObject,1f);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/// <summary>
/// 在地图上随机生成敌人,记录敌人总数,玩家得分,游戏结束后用退格键退出游戏
/// </summary>
public class EnemyGenerator : MonoBehaviour
{
//定义外部变量
public GameObject enemyPrefab;
public float enemyRange = 100f;
public int totalEnemy = 100;
public float CD = 1f;
private float timer = 0;
public static int enemyCount = 0;
public static int point = 0;
void Update()
{
//计时器开始计时
timer += Time.deltaTime;
//当计时器时间超过CD时间而且地图上的敌人数小于最高敌人数
if (timer > CD && enemyCount <= totalEnemy)
{
//计时器清零
timer = 0;
//重置CD
CD = Random.Range(0.3f, CD);
//计算随机位置
Vector3 pos = transform.position + Vector3.forward * Random.Range(-enemyRange, enemyRange) + Vector3.right * Random.Range(-enemyRange, enemyRange);
//在随机位置生成敌人
Instantiate(enemyPrefab, pos, transform.rotation);
//总敌人数加一
enemyCount++;
}
//按空格键退出游戏
if (Input.GetKey(KeyCode.Backspace))
{
Application.Quit();
}
}
}
using System.Collections;
using System.Collections.Generic;
using TMPro;
using UnityEngine;
//控制UI,在UI上实时更新敌人数和玩家得分
public class TextPoints : MonoBehaviour
{
TMP_Text textMesh;
void Start()
{
//获取TextMeshPro组件
textMesh = GetComponent<TMP_Text>();
}
void Update()
{
//打印敌人数和玩家得分
textMesh.text = "Total Enemy: " + EnemyGenerator.enemyCount + " Points: " + EnemyGenerator.point;
}
}

