private SpawnCell GetClosestCell() { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; int layerMask = 1 << LayerMask.NameToLayer("Ground"); if (Physics.Raycast(ray, out hit, maxDistance: 300.0f, layerMask: layerMask)) { hitPosition = hit.point; if (!placementVolume.bounds.Contains(hitPosition)) { hitPosition = placementVolume.bounds.ClosestPoint(hitPosition); } //now we'll look for objects within a radius, and find the closest object with CellScript SpawnCell closestCell = null; float closestDist = visibilityRadius + 1.0f; Collider[] hitColliders = Physics.OverlapSphere(hitPosition, visibilityRadius); for (int i = 0; i < hitColliders.Length; i++) { SpawnCell foundCell = hitColliders[i].GetComponent <SpawnCell>(); if (foundCell != null) { float dist = (foundCell.transform.position - hitPosition).magnitude; if (dist < closestDist) { closestCell = foundCell; closestDist = dist; } } } return(closestCell); } return(null); }
// Update is called once per frame void Update() { SpawnCell closest; switch (placementState) { case PlacementState.Begin: spawnCell = GetClosestCell(); if (placementVolume.bounds.Contains(hitPosition)) { moveTarget.position = hitPosition + new Vector3(0.0f, dragHeight, 0.0f); if (Input.GetMouseButtonUp(0) && spawnCell) { OnMouseUp(); } } break; case PlacementState.StartDrag: closest = GetClosestCell(); if (closest != spawnCell && placementVolume.bounds.Contains(hitPosition)) { spawnCell.SetItem(null); spawnCell = closest; placementState = PlacementState.Dragged; SendMessage("OnDrag", SendMessageOptions.DontRequireReceiver); Vector3 targetPosition = hitPosition + new Vector3(0.0f, dragHeight, 0.0f); moveTarget.position = targetPosition; } break; case PlacementState.Dragged: spawnCell = GetClosestCell(); moveTarget.position = hitPosition + new Vector3(0.0f, dragHeight, 0.0f); break; case PlacementState.Placed: break; case PlacementState.Invalid: if (CanPlace()) { placementState = PlacementState.Placed; moveTarget.position = spawnCell.transform.position; SendMessage("OnPlace", SendMessageOptions.DontRequireReceiver); } break; default: break; } }