I'm trying to spawn invisible walls around my screen dynamically through script and so far I've managed to find the bottomLeft, topLeft, topRight & bottomRight Vector3 coordinates.
I wrote this method to create a wall but the orientation of the wall seems to be off:
void SpawnWall(string wallName, Vector3 startPosition, Vector3 endPosition, Vector3 center)
{
// Create & center the wall between the start and end positions
GameObject wall = new GameObject(wallName);
wall.transform.position = (startPosition + endPosition) / 2;
BoxCollider wallCollider = wall.AddComponent<BoxCollider>();
// Adjust the collider size and position
wallCollider.size = new Vector3((endPosition - startPosition).magnitude, wallHeight, wallThickness);
// Make the wall face towards the center
//Vector3 direction = Vector3.Cross(startPosition, endPosition);
wall.transform.LookAt(center);
walls.Add(wall);
}
The red, blue, green & pink lines on the screen are the boundaries I'm trying to create the invisible walls. These are the positions I'm testing with:
Vector3 bottomLeft = new Vector3(-13.80, 0.00, -6.82);
Vector3 topLeft = new Vector3(-17.52, 0.00, 13.02);
Vector3 topRight = new Vector3(14.43, 0.00, 9.41);
Vector3 bottomRight = new Vector3(6.38, 0.00, -9.10);
I would appreciate any tips or advice on this matter. Thanks!
The following method places a wall (empty GameObject
with a BoxCollider
) between two positions. To address your objective I have introduced a couple of options, wasn't sure what exactly you were trying to achieve. The wall can be placed so that it connects the positions or is orthogonal to their connecting line. Also the wall's height can be aligned so that the bottom lies on the connecting line of the two positions. See the following implementation:
private void SpawnWallBetweenTwoVectors(string wallName, float wallHeight, float wallThickness, Vector3 v1, Vector3 v2, bool connect, bool alignBottom)
{
// Create wall
GameObject wall = new GameObject(wallName);
// Position wall at center between two vectors
wall.transform.position = v1 + 0.5f * (v2 - v1);
// Size wall to fill gap between two vectors
wall.transform.localScale = new Vector3((v2 - v1).magnitude, wallHeight, wallThickness);
if (!connect)
{
// Option 1: Rotate wall so that it stand between two vectors
// Just look at one of the two vectors
wall.transform.LookAt(v1);
}
else
{
// Option 2: Rotate wall so that it connects two vectors
// Look at one of the two vectors and rotate by 90°
wall.transform.LookAt(v1);
wall.transform.Rotate(transform.up, 90f);
}
if (alignBottom)
{
// Put bottom of wall at height of connecting line between vectors (otherwise centered in height)
wall.transform.transform.Translate(transform.up * wallHeight);
}
// Add collider
wall.AddComponent<BoxCollider>();
}