一、实现效果
效果图
功能列表
- 飞机定时无限发射
- 左右键控制飞机左右移动
- 随机生成怪物,怪物有不同
- 子弹射中怪物后,子弹和怪物一起被摧毁
二、知识点
刚体
- Dynamic 普通刚体 有质量
- Static 静态刚体 质量无穷(地面)
- Kinematic 运动学刚体 质量为0(物理规律不起作用,一般用于碰撞检测)
- 设置刚体:Physics 2D ->RigidBody 2D -> Body Type -> Dynamic/Static/Kinematic
碰撞体
- Physics 2D -> Box/Circle Collider 2D -> is Trigger
碰撞检测
- 设置可碰撞:添加碰撞组件Physics 2D ->Box Collider2D->is Trigger 打勾
- 添加碰撞检测函数(例):
private void OnTriggerEnter2D(Collider2D collision){Debug.Log("检测到了碰撞");}
Collider2D collision表示对方的碰撞组件
collision.gameObject——对方
collision.name——对方节点名称
collision.tag —— 对方的节点的Tag
collision.transform——对方的Transform组件
- 碰撞事件回调:
1、OnTriggerEnter2D,两碰撞体开始相遇
2、OnTriggerStay2D,两碰撞体接触中
3、OnTriggerExit2D,两碰撞体离开
随机数
value=Random.Range(min,max);
eg:float x=Random.Range(-2,2);
定时器
InvokeRepeating(method, delay,interval);//delay 多长时间后执行第一次,interval 几秒钟重复一次方法调用
eg:InvokeRepeating(“CreatePig”,0.1f ,2f);
随机选择图片
int index = Random.Range(0, images.Length);
SpriteRenderer renderer = monster.GetComponent();
renderer.sprite = this.images[index];
三、代码实现
MyGame.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyGame : MonoBehaviour
{
// Start is called before the first frame update
void Start()
{
Application.targetFrameRate = 60;
}
// Update is called once per frame
void Update()
{
}
}
MyBullet.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MyBullet : MonoBehaviour
{
public float speed = 2.0f;
// Start is called before the first frame update