我正在使用 Unity 3D C# 制作塔防游戏。目标是让玩家将对象放置在网格中(下面的网格代码)。我无法将“角”对象放置在地面上,它只是出现在我单击的 Y 轴上的任何位置。我很困惑,因为我对不同的项目使用了相同的脚本并且它工作正常(我只是将“墙”这个词换成了“角落”)。这些项目之间的唯一区别是一个是直线,一个是 L 形(我通过制作两个立方体,将它们组合并将它们作为一个名为“角”的子空游戏对象来做到这一点)。有任何想法吗?
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);
}
}
}
}
角落放置器:
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;
}
}