Unity学习笔记(2)飞机大战第二章「飞机定时无限发射」「左右键控制飞机左右移动」「随机生成预制体怪物」「子弹射中怪物后,子弹和怪物一起被摧毁」

这篇博客介绍了Unity中实现飞机大战游戏的关键技术,包括飞机定时发射、键盘控制移动、随机生成怪物以及碰撞检测机制。通过讲解刚体、碰撞体、碰撞检测和定时器等概念,展示了如何实现子弹与怪物碰撞后的销毁效果。作者还分享了在开发过程中遇到的预制体销毁问题及其解决方法。
摘要由CSDN通过智能技术生成

一、实现效果

效果图

在这里插入图片描述

功能列表

  1. 飞机定时无限发射
  2. 左右键控制飞机左右移动
  3. 随机生成怪物,怪物有不同
  4. 子弹射中怪物后,子弹和怪物一起被摧毁

二、知识点

刚体

  • 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
    
  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值