Hi everyone,
I’m creating a 3D platformer and i’m stuck with one of my scripts.
In my game the player can remove and place objects (Cubes actually).
So far I managed to make the player remove the right cubes but I just don’t see how to make the player to place a cube next to another one (snap it) when clicking on the face (something like minecraft snapping).
I searched and found a lot of things regarding how to build some minecraft gameplay but I never managed to make it work in my game.
There are 3 types of cube in my game :
Green: They are “Level cube” and cannot be removed but we can snap other cubes to them
Red : They are “Weak cubes” the can be removed and we can snap cubes to them
Blue : They are the “Player cubes” they can be placed and removed
For now i’m abble to remove red and blue cubes, but when i try to place a blue cube next to another one it goes right at the place of the cube i clicked on, i’m not sure if I explain that clearly what it does is that :
The 2 cubes are in the same place.(it does the same thing with de green cubes)
I tried to use a grid and layermasks (as found in one of the subjects about minecraft stuff in unityAnswer) but it didn’t worked (the cube was instantiated far from where i clicked)
I’m quite lost here if someone could help me that would be awesome !
Here is my code so far :
public float Range = 10.0f;
public GameObject Cube;
void Update()
{
if (Input.GetMouseButtonDown(1))
{
RaycastHit hitPoint;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hitPoint, Mathf.Infinity))
{
if(hitPoint.collider.tag == "PlayerCube" && (hitPoint.distance <= Range))
{
Destroy(hitPoint.collider.gameObject);
Debug.Log("Hit/Removed PlayerCube");
}
if(hitPoint.collider.tag == "LevelCube" && (hitPoint.distance <= Range))
{
Debug.Log("Hit/Can't Remove LevelCube");
}
if(hitPoint.collider.tag == "WeakCube" && (hitPoint.distance <= Range))
{
Destroy(hitPoint.collider.gameObject);
Debug.Log("Hit/Removed WeakCube");
}
}
else
{
Debug.Log ("No collider hit");
}
}
if (Input.GetMouseButtonDown(0))
{
RaycastHit hitPoint;
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
if(Physics.Raycast(ray, out hitPoint, Mathf.Infinity))
{
if(hitPoint.distance <= Range)
{
Instantiate(Cube, hitPoint.transform.position, Quaternion.identity);
Debug.Log("Placed a Cube");
}
}
}
}
Thanks for your help
And sorry for my bad english.