Hi there!
First of all, I am sorry if my english it’s hard to understand, it’s not my mother language.
I am working on a Housing System where the player will be able to generate new rooms of different styles and sizes, and place different furnitures and objects around to decorate and use. The first part (all the room-oriented stuff) is complete, but when beginning the second half I have encountered a problem and I can’t manage to continue:
Right now, I am using a simple cube as a test object which has a script that:
— Snaps the object on a “grid” by autopositioning itself only on positions with an entire value or a half exactly (0.5,1,1.5, 2 etc)
— And a OnMouseDown function which changes a bool in order to activate a section of a FixedUpdate and move the object around to the mouse position.
The problems or things that I can’t work around are:
— As much as I press the mouse, once the cube it’s grabbed it won’t just release itself.
— I can only move the cube to the right of the left of my character, never forward or backward, as I don’t get how to set the raycast to move the cube without getting off the borders of the room or moving like crazy ignoring the Grid system.
Here’s the code:
using System.Collections;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class SnapToGrid : MonoBehaviour {
public float grid = 0.5f;
public Color HoverColor;
private Color OriginalColor;
public bool IsGrabbed;
float x = 0;
float z = 0;
float distance = 2;
private void Awake()
{
OriginalColor = this.GetComponent<Renderer>().material.color;
}
//Grid System of 0.5
void Update ()
{
if (grid > 0) {
float reciprocalGrid = 1f / grid;
x = Mathf.Round(transform.position.x * reciprocalGrid) / reciprocalGrid;
z = Mathf.Round(transform.position.z * reciprocalGrid) / reciprocalGrid;
transform.position = new Vector3(x, 0.5f, z);
}
}
private void FixedUpdate()
{
if (IsGrabbed == true)
{
this.GetComponent<BoxCollider>().enabled = false;
Vector3 mousePosition = new Vector3(Input.mousePosition.x, Input.mousePosition.y, distance);
Vector3 objPosition = Camera.main.ScreenToWorldPoint(mousePosition);
transform.position = objPosition;
if (Input.GetMouseButtonDown(1))
{
IsGrabbed = false;
}
}
}
private void OnMouseEnter()
{
this.GetComponent<Renderer>().material.color = HoverColor;
}
private void OnMouseExit()
{
this.GetComponent<Renderer>().material.color = OriginalColor;
}
private void OnMouseDown()
{
IsGrabbed = !IsGrabbed;
if (IsGrabbed == false)
{
this.GetComponent<BoxCollider>().enabled = true;
}
}
}
Here’s a quick recording of the cube as it acts right now: Imgur: The magic of the Internet
Any help or guide to follow?