Question by
salsa · Jun 22, 2017 at 10:21 AM ·
physicscolliderplacementphysics.overlapsphere
How to do a Placement object properly?
Hi guys,
I'm trying to implement a object placement functionality, and I don't know what I'm doing wrong.
I would like to detect if already have an item in the same place that I'm trying to drop.
I already try a lot of things, lately I alsohave added a Layer but doesn't works too :(
Any help please!
Here is what I did:
using UnityEngine;
public class Test : MonoBehaviour
{
private GameObject Entity;
private BoxCollider Box;
private void Start()
{
CreateObjectTest();
}
private void CreateObjectTest()
{
Entity = new GameObject();
GameObject Prefab = Instantiate(Resources.Load("Prefabs/Props/dumpster_mesh")) as GameObject;
Prefab.transform.parent = Entity.transform;
Box = Prefab.AddComponent<BoxCollider>();
Entity.layer = LayerMask.NameToLayer("PlacementItem");
}
private void FixedUpdate()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
// Move object to mouse position
Vector3 Pos = new Vector3(Mathf.Round(hit.point.x), 1, Mathf.Round(hit.point.z));
Entity.transform.position = Pos;
// On click, ty to place item
if (Input.GetMouseButtonDown(0))
{
if (IsHitting(hit.collider, Entity.layer))
{
Debug.Log("found something blocking");
}
else
{
CreateObjectTest();
}
}
}
}
public bool IsHitting(Collider col, int Mask)
{
Collider[] hits = Physics.OverlapBox(col.bounds.center, col.bounds.extents, col.transform.rotation, Mask);
foreach (Collider hit in hits)
{
if (hit == col)
{
return true;
}
}
return false;
}
}
Comment