I have created 2 cubes, a small and a big one, I want the user to be interactif with the first cube, meaning, when the user make a left click and hold on, he should be able to move that cube then placed in the bigger one, like a regular drag and drop movement. can somebody please help me?
This script can be attached to any GameObject in your scene and your camera must have the tag “MainCamera”. It also changes the color of the selected object to make it more visible among the other objects in the scene.
You can also add a “GetMouseButtonUp” if you want.
using UnityEngine;
using System.Collections;
public class DragObject : MonoBehaviour
{
private Transform target = null;
private Color originalColor = Color.clear;
public Color selectedColor;
public float vel;
public void Update()
{
// Test if Left button was pressed and there was
// no object selected
if (Input.GetMouseButton(0) && target == null)
{
// Cast a Ray from Camera Position
Vector3 v = new Vector3(Input.mousePosition.x,
Input.mousePosition.y,0);
Ray ray = Camera.main.ScreenPointToRay(v);
// This object will store the closest object
// in front of the camera
RaycastHit hit;
// Test if there’s something in front of the camera
if (Physics.Raycast(ray, out hit))
{
// Hide the Cursor
Screen.showCursor = false;
target = hit.transform;
if (target.renderer.material != null)
{
if (originalColor == Color.clear)
originalColor = target.renderer.material.color;
target.renderer.material.color = selectedColor;
}
}
}
// Reset the target if Left button was released
else if (Input.GetMouseButtonUp(0) && target != null)
{
// Show Cursor again
Screen.showCursor = true;
if (target.renderer.material != null)
{
target.renderer.material.color = originalColor;
originalColor = Color.clear;
}
target = null;
}
// Move the target
if (target != null)
{
Vector3 moved = new Vector3(Input.GetAxis(“Mouse X”),
Input.GetAxis(“Mouse Y”),0);
target.position += moved;
}
}
}
Please, check the question if solve to another user use this too