How to check if object is inside another
Im creating a city building game, and i need to check if the building is 100% inside the grid, which is currently a 3d cube (using only the X and Z coordinates of the building) i thought to take the maximum coordinates of the cube and calculate it with the construction coordinates (like the example below) in a autmotatic way that i dont need to do this for every single construction. But i dont know if this will work and i dont know how to do this. Some help ?
Answer by AlgoUnity · Sep 22, 2021 at 11:11 AM
You basically want to use a Rect struct (built-in to Unity) for each of those buildings that represents its 2D position on the grid and its height/width. You only need to check that the bottom left corner of the building is greater than the bottom left corner of the grid, and the top right corner of the building is less than the top right corner of the grid. You can decide that a building's position is its bottom left corner, to make it very easy to do these calculations:
public bool BuildingIsInsideBounds(Rect buildingRect, Rect gridRect)
{
return buildingRect.x > gridRect.x && //left side is inside
buildingRect.y > gridRect.y && //bottom side is inside
buildingRect.x + buildingRect.width < gridRect.x + gridRect.width && //right
buildingRect.y + buildingRect.height < gridRect.y + gridRect.height; //top
}
Actually, Rect has some functions built in that you can use to make it even simpler if you want.
Your answer
Follow this Question
Related Questions
3d grid/matrix inside a mesh 1 Answer
How do I obtain smooth movement of a 3d object on an int grid? 0 Answers
Player Controls For Restricted Directional Movement, but those things vary... 0 Answers
Grid/TileMap rotation not affecting child GameObjects? 0 Answers
How to speed up building at game? 1 Answer