制作3d游戏软件手机版中文 (制作游戏3d版)

5.板栗生成器

5.1 创建板栗的 Prefab

在层级窗口中将板栗拖拽到工程窗口中并命名为 igaguriPrefab,同时将层级窗口中的板栗删除。

5.2 编写板栗生成器脚本

在工程窗口中右击,选择 Create -> C# Script,并命名为 IgaguriGenerator。代码如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class IgaguriGenerator : MonoBehaviour
{
    public GameObject igaguriPrefab;
    
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            GameObject igaguri = Instantiate(igaguriPrefab) as GameObject;
            igaguri.GetComponent<IgaguriController>().Shoot(new Vector3(0, 300, 2000));
        }
    }
}

在上面的代码中,首先声明了一个存放板栗的 Prefab 对象,在后面还需要在检视器窗口中对其赋值,所以声明为 public。

在 Update() 方法中,通过 GetMouseButtonDown 方法来检测画面是否被单击,如果单击则生成板栗,并且通过 GetComponent 方法获取其控制器脚本后调用 Shoot 方法让板栗飞出去。

这时,需要注意,因为我们已经删除了板栗对象,所以同时需要删除控制器脚本中 Start 方法中的对应的 Shoot 调用,或者注释掉也可以。

5.3 创建板栗工程对象

创建一个空对象,在层级窗口中选择 Create -> Create Empty,命名为 IgaguriGenerator。

将生成器脚本挂载到该对象上。

5.4 将 Prefab 传递给工厂

在层级窗口中选中 IgaguriGenerator 空对象,在检视器窗口中可以看到脚本中声明的 public 成员:igaguriPrefab,从工程视图中将 igaguriPrefab 推拽到此处。

启动游戏,看看效果!

5.5 让板栗从单击位置飞出去

现在板栗只能从固定的方向飞出去,最好的效果是从单击的位置飞出去,要做到这一点,首先要获取单击位置的坐标,我们可以通过 Input.mousePosition 方法来获取鼠标的单击位置的坐标,但在 3D 游戏中鼠标的坐标值不能直接使用,因为 mousePosition 表示的坐标不是世界坐标系而是本地坐标系的值。Unity 提供了 ScreenPointToRay 方法,获得的是一个世界坐标系统中从摄像机指向本地坐标的向量。

修改生成器脚本如下:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class IgaguriGenerator : MonoBehaviour
{
    public GameObject igaguriPrefab;
    
    // Start is called before the first frame update
    void Start()
    {
        
    }

    // Update is called once per frame
    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            GameObject igaguri = Instantiate(igaguriPrefab) as GameObject;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
            Vector3 dir = ray.direction;
            igaguri.GetComponent<IgaguriController>().Shoot(dir.normalized * 2000);
        }
    }
}

启动游戏,看看效果吧!