- Home /
Grid-based building system not working
Hey.
I'm making a survival game and I am trying to build a building system similar to Rust.
This is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SnapToGrid : MonoBehaviour {
public GameObject buildingPrefab;
public float gridDistance = 2f;
float gridSize;
Vector3 gridPosition;
Vector3 worldPosition;
void Start() {
worldPosition = transform.position;
gridSize = 1f / gridDistance;
}
void Update() {
gridSize = 1f / gridDistance;
Ray ray = Camera.main.ScreenPointToRay(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 0f));
RaycastHit hit;
Physics.Raycast(ray, out hit);
worldPosition = hit.point;
//Vector3 distanceVec = hit.point - Camera.main.transform.position;
//worldPosition -= distanceVec.normalized * (distanceVec.magnitude - 1f);
gridPosition = new Vector3(
Mathf.Round(worldPosition.x * gridSize) / gridSize,
Mathf.Round(worldPosition.y * gridSize) / gridSize,
Mathf.Round(worldPosition.z * gridSize) / gridSize);
transform.position = gridPosition;
if(Input.GetMouseButtonDown(0)) {
Instantiate(buildingPrefab, gridPosition, Quaternion.identity);
}
}
}
There is a preview where the raycast from the camera comes in contact with a collider, and whenever you click it will instantiate the building in the place where the preview is.
HOWEVER... The problem I currently have is whever you try to place a building on the side of another building, it clips through and goes inside that building.
This makes it impossible to place one building on the side of another, and it also makes it so you can stack multiple buildings in the exact same position. These are both things I do not want.
Do you guys know of any way to make the preview on the side of the placed building instead of inside it? Thanks, Rugbug
Use Physics.Boxcast to check if any existing buildings are in the space. If yes, compare the construction space center with the existing building's center to find the side of the existing building that is nearest, and then move the space accordingly to it sits next to the existing building.
Answer by EnigmaticCrow · Apr 11, 2018 at 06:48 PM
I did a similar thing a while ago and had the same problem. My solution was to add the (normalized) normal of the surface you've hit to the point of the raycasthit before rounding it to the gridposition. You can get the normal of the mesh at a specific point by using RayCastHit.triangleIndex and taking the average of the three normals.
Thanks a ton!
Vector3 newPos = hit.point + hit.normal.normalized;
is what I ended up doing
Your answer
Follow this Question
Related Questions
mouse position percentage problem 0 Answers
Keeping track of which areas remain unexplored 1 Answer
How to handle Grid Boxes properly? 1 Answer
The 'correct' way to deal with animations in a grid-based game? 1 Answer
Block puzzle (1010) help 0 Answers