- Home /
Collision check on Placement
First time poster here. I have been working something small for a few days now. The basic idea is that you place items in a game world, like a strategy game. Right now I have a first script for simply placing an item (GUI and multiple items will be implemented later) and all I have left is to check for collisions between objects, so that if an object about to be placed will overlap an already existing object it will simply not happen. Thing is I'm doing all of this in void Update and everything I've seen online uses some other class, like void OnCollision. Does anyone know how to write these kinda things in void Update? Below is the complete code.
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class victorsBuildingManager : MonoBehaviour { bool preview = false; public GameObject building;
void Update ()
{
if (Input.GetKeyDown (KeyCode.Alpha1))
{
preview = true;
}
if (preview == true)
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Physics.Raycast(ray, out hit);
building.transform.position = hit.point;
}
if (Input.GetMouseButtonDown(0))
{
//Check for collision
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
Physics.Raycast(ray, out hit);
if (/*collision exists*/)
{
Destroy(building);
preview = false;
}
if (/*no collision*/)
{
Destroy(building);
preview = false;
Instantiate(building, hit.point, Quaternion.identity);
}
}
}
}
Answer by teal_dragon · Nov 30, 2016 at 10:10 PM
it looks to me that you would have to check for the outer bounds of your objects to test the collision; example:
center of object = (x,y); edge of object = 3; //measured in units from center
if(center of object +/- edge == other object +/- other edge) collision happening