实例化漂浮在空中的游戏对象

时间:2019-11-23 15:53:07

标签: c# unity3d

我正在用Unity 3D C#开发塔防游戏。目标是让玩家将对象放置在网格中(下面的网格代码)。我无法将“角”对象放置在地面上,它只是出现在我单击的Y轴上的任何位置。我很困惑,因为我在不同的项目上使用了完全相同的脚本,并且效果很好(我只是将“ wall”改为“ corner”)。这些项目之间的唯一区别是,一个是直线,一个是L形(我通过制作两个立方体,将它们组合在一起,然后将它们作为称为“角”的子级Empty游戏对象来实现)。有什么想法吗?

using UnityEngine;

public class Grid : MonoBehaviour
{
    [SerializeField]
    private float size = 1f;

    public Vector3 GetNearestPointOnGrid(Vector3 position)
    {
        position -= transform.position;

        int xCount = Mathf.RoundToInt(position.x / size);
        int yCount = Mathf.RoundToInt(position.y / size);
        int zCount = Mathf.RoundToInt(position.z / size);

        Vector3 result = new Vector3(
            (float)xCount * size,
            (float)yCount * size,
            (float)zCount * size);

        result += transform.position;

        return result;
    }

    private void OnDrawGizmos()
    {
        Gizmos.color = Color.yellow;
        for (float x = 0; x < 40; x += size)
        {
            for (float z = 0; z < 40; z += size)
            {
                var point = GetNearestPointOnGrid(new Vector3(x, 0f, z));
                Gizmos.DrawSphere(point, 0.1f);
            }

        }
    }
}

CornerPlacer:

using UnityEngine;

public class CornerPlacer : MonoBehaviour
{
    private Grid grid;
    public GameObject corner;
    public bool placeCornerMode;

    private void Awake()
    {
        grid = FindObjectOfType<Grid>();
    }
    void Update()
    {
        if (placeCornerMode)
        {
            GetItemsCorner();
        }
    }
    void GetItemsCorner()
    {
        if (Input.GetMouseButtonDown(0))
        {
            RaycastHit hitInfo;
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out hitInfo))
            {
                PlaceCornerNear(hitInfo.point);
                placeCornerMode = false;
            }
        }
    }
    private void PlaceCornerNear(Vector3 clickPoint)
    {
        var finalPosition = grid.GetNearestPointOnGrid(clickPoint);
        Instantiate(corner, finalPosition, Quaternion.identity);
    }
    public void CornerModeOn()
    {
        placeCornerMode = true;
    }
}

0 个答案:

没有答案