如何实现在方块上方一定距离生成物体

希望可以在方块上方随机生成无敌,具体高度可以调节
这是我使用的随机生成脚本:

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



public class RandomPlace : MonoBehaviour

{

    public Transform[] SpawnPoints;//存放生成位置

    public GameObject prefab;//生成的物体



 



    public float spawnTime = 3f;//多长时间后调用

    public float nextSpawnTime = 2f;//下一个物体生成的时间



    // Start is called before the first frame update

    void Start()

    {

        InvokeRepeating("SpawnPrefab", spawnTime, nextSpawnTime);

        //"SpawnPrefabs" : 调用的方法名称

        //spawnTime: 多长时间后调用

        //nextSpawnTime: 下一个物体生成的时间

    }

    private void SpawnPrefab()

    {

        int Index = Random.Range(0, SpawnPoints.Length);//生成位置数组下标



        //随机生成一个数组的下标

        Instantiate(prefab, SpawnPoints[Index].position, SpawnPoints[Index].rotation);

        //prefab: 生成的物体

        //SpawnPoint[Index].position: 生成的物体所在的位置

        //SpawnPoint[Index].rotation: 生成物体的角度

    }

}


这是脚本页面

img

从哪里设置可以让生成物以一定高度生成呢?

您可以在 SpawnPrefab() 方法中,生成物体时,将 SpawnPoints[Index].position 向上偏移一定高度,从而实现在方块上方随机生成的效果。例如,将 SpawnPoints[Index].position 的 y 坐标值增加一个常量值 heightOffset,如下所示:


private void SpawnPrefab()
{
    int Index = Random.Range(0, SpawnPoints.Length);//生成位置数组下标
    Vector3 spawnPosition = SpawnPoints[Index].position + new Vector3(0f, heightOffset, 0f);
    Instantiate(prefab, spawnPosition, SpawnPoints[Index].rotation);
}

其中,heightOffset 表示偏移的高度值,您可以根据需要进行调整。