我的游戏中有一个构建机制,我想知道如何才能让它在我放置对象时它会捕捉到网格。每当我按下 0 时,它会将对象移动到我的鼠标上,每当我单击它时,它都会将对象放下。我想让它在放置时捕捉到网格,这样对象就不会发生碰撞。
using UnityEngine;
using UnityEngine.AI;
public class GroundPlacementController : MonoBehaviour
{
[SerializeField]
private GameObject placeableObjectPrefab;
public NavMeshObstacle nav;
[SerializeField]
private KeyCode newObjectHotkey = KeyCode.A;
private GameObject currentPlaceableObject;
private float mouseWheelRotation;
private void Update()
{
HandleNewObjectHotkey();
nav = GetComponent<NavMeshObstacle>();
if (currentPlaceableObject != null)
{
MoveCurrentObjectToMouse();
RotateFromMouseWheel();
ReleaseIfClicked();
}
}
private void HandleNewObjectHotkey()
{
if (Input.GetKeyDown(newObjectHotkey))
{
if (currentPlaceableObject != null)
{
Destroy(currentPlaceableObject);
}
else
{
currentPlaceableObject = Instantiate(placeableObjectPrefab);
}
}
}
private void MoveCurrentObjectToMouse()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hitInfo;
if (Physics.Raycast(ray, out hitInfo))
{
currentPlaceableObject.transform.position = hitInfo.point;
currentPlaceableObject.transform.rotation = Quaternion.FromToRotation(Vector3.up, hitInfo.normal);
currentPlaceableObject.GetComponent<NavMeshObstacle>().enabled = false;
}
}
private void RotateFromMouseWheel()
{
Debug.Log(Input.mouseScrollDelta);
mouseWheelRotation += Input.mouseScrollDelta.y;
currentPlaceableObject.transform.Rotate(Vector3.up, mouseWheelRotation * 90f);
}
private void ReleaseIfClicked()
{
if (Input.GetMouseButtonDown(0))
{
currentPlaceableObject.GetComponent<NavMeshObstacle>().enabled = true;
print("disabled");
currentPlaceableObject = null;
print("removed prefab");
}
}
}
最佳答案
您可以通过简单地将 transform.position
的每个轴四舍五入来捕捉到代码中的网格:
var currentPosition = transform.position;
transform.position = new Vector3(Mathf.Round(currentPosition.x),
Mathf.Round(currentPosition.y),
Mathf.Round(currentPosition.z));
关于c# - 使可放置对象与网格对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55184124/