private void FixedUpdate() { //Perform raycast Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(camRay, out hit, 1000f, hitLayers)) { //check if the grid is hit IPlacementArea placement = hit.collider.GetComponent <IPlacementArea>(); //get grid point if (placement != null) { //snap position of tower to the grid element transform.position = placement.Snap(hit.point, new IntVector2(1, 1)); } } }
public void FixedUpdate() { if (Input.GetMouseButtonDown(0)) { Ray camRay = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(camRay, out hit, 1000f, hitLayers)) { //Check if hitting grid IPlacementArea placement = hit.collider.GetComponent <IPlacementArea>(); if (placement != null) { //Snap position tower to Grid element transform.position = placement.Snap(hit.point, new IntVector2(1, 1)); } } } }
private void Update() { // Check collisions with placement areas var mouseRay = HelperObjects.CameraComponent.ScreenPointToRay(Input.mousePosition); RaycastHit areaHit; Physics.Raycast(mouseRay, out areaHit); // Clear all potential tiles when leaving area if (targetArea == null && !firstPlacement) { clearAllOldTiles(); } if (areaHit.collider != null) { targetArea = areaHit.collider.GetComponent <IPlacementArea>(); if (targetArea != null) { // If first placement, instantly move and enable if (firstPlacement) { firstPlacement = false; transform.position = areaHit.point; transform.localScale = Vector3.one; return; } var snappedPosition = targetArea.Snap(areaHit.point, SizeOffset); var snappedGridPosition = targetArea.WorldToGrid(areaHit.point, SizeOffset); // Check if the ghost fits and isn't too close to the path var fits = targetArea.Fits(snappedGridPosition, SizeOffset) == TowerFitStatus.Fits; Collider[] collisions = Physics.OverlapSphere(areaHit.point, PathCollisionRadius); var collidesWithPath = collisions.Any((c) => c.gameObject.layer == Constants.PATH_LAYER); if (fits && !collidesWithPath) { transform.localScale = Vector3.one; // Set new position and update placement tile state if (snappedPosition != targetPosition) { clearOldTiles(); targetArea.Occupy(snappedGridPosition, SizeOffset, PlacementTileState.Potential); targetPosition = snappedPosition; } } } } // Move ghost if (Vector3.SqrMagnitude(transform.position - targetPosition) > 0.01f) { transform.position = Vector3.SmoothDamp(transform.position, targetPosition, ref velocity, Dampening); } else { velocity = Vector3.zero; } // Build when clicked if (Input.GetMouseButtonDown(0)) { if (targetArea != null && !GameManager.IsUiBlocking) { BuildManager.I.ImplementMitigation( targetArea, targetArea.WorldToGrid(targetPosition, SizeOffset), SizeOffset); DestroyGhost(); } } else if (Input.GetMouseButtonDown(1) || Input.GetKeyDown(KeyCode.Escape)) { clearAllOldTiles(); enabled = false; DestroyGhost(); } }