太空大战–主角创建
前言
该博客为记录学习太空大战unity项目的过程。
游戏介绍
在游戏中,主角操作太空飞船和敌人的太空飞船战斗。消灭敌人的飞船可以取得一定的分数,游戏没有尽头,除非主角的飞船被击落,则游戏结束。
脚本创建
把Project视图中的Player.fbx模型文件拖动到Hierarchy视图当中去。
在Project视图中创建一个Folder名为Scripts用来存放脚本。
进入Scripts目录鼠标右键选择Create->C# Script创建一个Player.cs脚本。
打开Player.cs,会发现Unity已经创建好了一部分代码。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
}
}
将Player.cs拖动到Hierarchy视图下的Player.fbx模型上将脚本指定为主角游戏提的组件。
控制飞船移动
打开Player.cs,修改代码如下。
1、添加一个获取模型Transform组件的属性
Transform m_transform;
// Start is called before the first frame update
void Start()
{
m_transform = this.transform;
}
2、添加一个控制飞行速度的属性
public float m_speed = 1;
3、修改Update函数
void Update()
{
//x轴方向移动的距离
float moveh = 0;
//z轴方向移动的距离
float movev = 0;
if (Input.GetKey(KeyCode.UpArrow))
{
movev += Time.deltaTime * m_speed;
}
if (Input.GetKey(KeyCode.DownArrow))
{
movev -= Time.deltaTime * m_speed;