Unity官方案例-Space Shooter学习笔记(2)

本文介绍了Unity中的Space Shooter案例,包括如何设定游戏边界以自动销毁超出范围的物体,以及创建敌人陨石并实现其随机旋转、碰撞消除、爆炸效果和持续生成。详细讲解了使用OnTriggerExit、Destroy、Rigidbody.angularVelocity等关键代码及协同程序(coroutine)的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、边界设定

现在有一个问题,射出去的子弹物体不会消失,不断射出子弹会不断产生新的GameObject,所以我们需要设定一个游戏区域,使得超出边界的物体自动消失。

首先生产生成一个正方体,调整角度和大小,使之略大于画面显示范围,并且删除Render,使之在屏幕中不可见。而后利用该正方体的Collider,来实现删除掉超出边界的物体的功能。完成后的效果大致如下:

div align=center


之后我们要编辑该边界的脚本,使之实现删除超出其范围的物体的功能。利用到的代码有"OnTriggerExit"和"Destroy"。先看官方说明:

Object.Destroy

public static void Destroy (Object obj, float t= 0.0F);

项目 含义
obj 破壊するオブジェクト
t オブジェクトを破壊するまでのディレイ時間

ゲームオブジェクトやコンポーネント、アセットを削除します。

t 秒後にオブジェクトの obj を破壊します。 obj は Component の場合、GameObjectからコンポーネントを削除し、破壊します。 obj が GameObject の場合、GameObject ならびにすべてのコンポーネント、GameObject の子であるすべてのオブジェクトを破壊します。 オブジェクトの破壊は、現在のフレームのアップデート(Update)処理後に行われますが、常にレンダリング前に実行されます。

官方示例代码:

using UnityEngine;

public class ScriptExample : MonoBehaviour
{
   
   
    void DestroyGameObject()
    {
   
   
        Destroy(gameObject);
    }

    void DestroyScriptInstance()
    {
   
   
        // Removes this script instance from the game object
        Destroy(this);
    }

    void DestroyComponent()
    {
   
   
        // Removes the rigidbody from the game object
        Destroy(GetComponent<Rigidbody>());
    }

    void DestroyObjectDelayed()
    {
   
   
        // Kills the game object in 5 seconds after loading the object
        Destroy(gameObject, 5);
    }

    // When the user presses Ctrl, it will remove the
    // BoxCollider component from the game object
    void Update()
    {
   
   
        if (Input.GetButton("Fire1") &amp;&amp; GetComponent<BoxCollider>())
        {
   
   
            Destroy(GetComponent<BoxCollider>());
        }
    }
}

OnTriggerExit:

Collider.OnTriggerExit(Collider other)
other : この衝突に含まれるその他の Collider

説明
Collider が other のトリガーに触れるのをやめたときに OnTriggerExit は呼び出されます。

This message is sent to the trigger and the Collider that touches the trigger. Notes: Trigger events are only sent if one of the Colliders also has a Rigidbody attached. Trigger events will be sent to disabled MonoBehaviours, to allow enabling Behaviours in response to collisions. OnTriggerExit occurs on the FixedUpdate after the Colliders have stopped touching. The Colliders involved are not guaranteed to be at the point of initial separation.

See Also: Collider.OnTriggerEnter which contains a useful example.

官方示例代码:

public class ExampleClass : MonoBehaviour
{
   
   
    void OnTriggerExit(Collider other)
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值