I have a game that spawns multiple gameobjects (at the moment, chairs) and I want to let the player move the chairs within a room. The chairs must not go out of the room. I’m using a drag and drop script and also a raycast to keep the chair stuck to the ground.
void OnMouseDrag()
{
Plane plane = new Plane(Vector3.up, new Vector3(0, 0, 0));
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
float distance;
if (plane.Raycast(ray, out distance))
{
transform.position = ray.GetPoint(distance);
}
if (Input.GetKeyDown(KeyCode.Q))
{
transform.Rotate(0, 15, 0);
}
if (Input.GetKeyDown(KeyCode.E))
{
transform.Rotate(0, -15, 0);
}
if (Input.GetKeyDown(KeyCode.Delete))
{
Destroy(this.gameObject);
}
//if (Input.GetKeyDown(KeyCode.T))
//{
// GetComponent<Renderer>().material.color = new Color(0, 0, 0);
//}
}
Empty gameobject that acts as parent to the chair with sticktoground script attached to it
void Update () {
RaycastHit hit;
if(Physics.Raycast(this.gameObject.transform.position, Vector3.down, out hit))
{
this.gameObject.transform.position = hit.transform.position;
}
}
In short, what methods can I use to keep the chairs from exiting the room.