一、效果图
大概的效果图如下,实现的功能:😁通过点击鼠标飞机会射出子弹,若子弹超出屏幕外会自动销毁。
二、功能实现
1、场景对象
- 【Main Camera】 代表主摄像机,需要这个我们才能看到如今这个视角
- 【游戏主控】 上面不挂载任何图片对象,但挂了一个c#文件,主要用来全局设置。比如这个项目所涉及到的时间针率。
3.【子弹】 这个子弹可惜忽略,主要是通过它来创建子弹预制体
4.【子弹Prefab】此对象需要挂MyBullet,特别提醒需要在【飞机】脚本下挂它
5.【飞机】 挂MyJet
2、代码实现
- 游戏主控—MyGame代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyGame : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
//设置帧率为60
//Application:应用
//target:目标
//Frame:帧
//Rate:率
Application.targetFrameRate= 60;
}
// Update is called once per frame
void Update()
{
}
}
- 子弹Prefab—MyBullet代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyBullet : MonoBehaviour
{
//在inspector中会出现【speed】,并且可以自由设置参数
public float speed = 5.5f;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//设置每刷新一次y轴的坐标,y轴坐标随时间增加,即表现为向上的运动
float dy = speed * Time.deltaTime;
//将空间坐标翻译赋给transform
transform.Translate(0, dy, 0, Space.Self);
//创建对象(而这个对象的坐标由transform提供)表现形式由主摄像机的世界坐标表示
Vector3 sp = Camera.main.WorldToScreenPoint(transform.position);
//如果对象的y坐标超过屏幕的高度则被摧毁
if (sp.y > Screen.height)
{
Destroy(this.gameObject);
}
}
}
- 飞机—MyJet代码
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyJet : MonoBehaviour
{
public GameObject myPrefab;
private float interval = 0.4f;
private float count = 0;
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
//如果鼠标按下,就射出子弹
if(Input.GetMouseButtonDown(0))
{
Fire();
}
}
private void Fire()
{
//创建预制体
//Instantiate:示例
GameObject bullet = Instantiate(myPrefab);
//子弹的位置=飞机所在位置的y轴加1
bullet.transform.position = transform.position + new Vector3(0, 1f, 0);
}
}
三、总结
现在我只是刚开始,给自己打气遇到挫折难题不要放弃,踏踏实实学习,一定会在毕业前修炼成大师的!
对的,这个游戏还没结束,下一章会继续写键盘控制飞机、子弹击中敌人,敌人消失。😊😊😊😊下一章见!