如何用键盘控制GameObject移动
FixedUpdate函数中添加如下代码
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
Vector3 movement = new Vector3(moveHorizontal, 0.0f, moveVertical);
rigidbody.velocity = movement * speed;
Input.GetAxis 可以通过Axes的名称获取移动的距离,范围为-1…1,至于GetAxis参数里的名称,可以通过InputManager来设置,Speed设置为公有变量,通过外界来设置移动的速度
2D游戏如何设置摄像机
Projection设置为Orthographic,即正交视图,此视图下摄像机看到的内容与物体与摄像机的距离无关,Size可以设置摄像机范围大小,Clipping Planes可以设置可以看到最近和最远的距离,Viewport Rect为摄像机显示的区域,可以通过它与Depth配合显示画中画
如何将物体移动限制在一定区域内
在FixedUpdate中添加如下代码
rigidbody.position = new Vector3
(
Mathf.Clamp(rigidbody.position.x,boundary.xMin,boundary.xMax),
0.0f,
Mathf.Clamp(rigidbody.position.z,boundary.zMin,boundary.zMax)
);
Rigidbody为GameObject挂载的刚体组件
Mathf.Clamp将第一个参数的值限制在min和max之间
Mathf.Clamp(value,min,max) 如果value小于min,返回min,如果value大于max,返回max,否则返回value
如何发射子弹,控制子弹发射的位置和发射频率
if(Input.GetButton("Fire1") && Time.time > nextFire)
{
nextFire = Time.time + fireRate;
Instantiate(shot, shotSpawn.position, shotSpawn.rotation);
}
Shot为子弹的GameObject,shotSpawn为子弹的发射位置,可以在飞机上添加一个子GameObject,利用相对位置来设置
如何让子弹运动起来
Start函数中添加如下代码
rigidbody.velocity = transform.forward * speed;
在Start函数中设置刚体的速度即可,因为刚体具有惯性,没有遇到阻力的话,可以一直运动下去
如何让子弹和陨石越过游戏区域后自动销毁
在场景中添加一个Cube,移除Mesh Renderer,因为不需要其在场景中显示,编辑Box Collider,将其包围整个游戏场景,任何飞出游戏区域的物体都会与其发生碰撞,这时销毁碰撞的物体即可。为其添加脚本如下
void OnTriggerExit(Collider other)
{
Destroy(other.gameObject);
}
如何为游戏添加背景
添加一个Quad,设置其旋转角度,和缩放值,将贴图直接拖放到Quad上,Shader可以选择 Unlit/Texture
如何为飞机添加尾部喷气效果
首先制作好粒子系统,将粒子系统拖动到飞机模型上即可
如何产生子弹击中敌人和飞船撞击到敌人的爆炸效果
为敌人添加脚本,内容如下
void OnTriggerEnter(Collider other)
{
if(other.tag !="Boundary")
{
Instantiate(explosion,transform.position,transform.rotation);
if (other.tag == "Player")
{
Instantiate(playerExplosion, other.transform.position, other.transform.rotation);
}
Destroy(other.gameObject);
Destroy(gameObject);
}
}
如何销毁游戏过程中动态产生的粒子效果
为粒子效果添加脚本,内容如下
void Start ()
{
Destroy(gameObject,lifeTime);
}
如何让敌人随机旋转
为敌人添加脚本
void Start ()
{
rigidbody.angularVelocity = Random.insideUnitSphere * tumble;
}
angularVelocity为角速度,Random.insideUnitSphere,随机获取半径为1的球体内的一个点坐标。
如何生成一波波的敌人
添加一个GameObject,为其添加如下脚本
void Start ()
{
StartCoroutine(SpawnWaves());
}
IEnumerator SpawnWaves()
{
yield return new WaitForSeconds(startWait);
while (true)
{
for (int i = 0; i < hazardCount; i++)
{
Vector3 spawnPosition = new Vector3(Random.Range(-spawnValues.x,spawnValues.x),
spawnValues.y,spawnValues.z);
Quaternion spawnRotation = Quaternion.identity;
Instantiate(hazard,spawnPosition,spawnRotation);
yield return new WaitForSeconds(spawnWait);
}
yield return new WaitForSeconds(waveWait);
}
StartCoroutine 开启一个协同程序,可以理解为创建了一个线程,与主UI无关