Ramaditya Alvian
Ramaditya Alvian

Reputation: 11

Following instruction for drag and drop 3d object unity but not working

Hi so i have followed every instruction from youtube videos (https://m.youtube.com/watch?v=NMt6Ibxa_XQ) but in the game mode i still cant drag and drop my cube, the cube just stay still when i click and drag it. This problem really gave me a headache i’m pretty sure i have followed every detail from the video and repeat it over and over, thank’s for your time and help i really appreciate and need it, thank youi

Upvotes: 0

Views: 3133

Answers (2)

Qusai Azzam
Qusai Azzam

Reputation: 530

use this script in order to drad and drop 3D Objects :

using UnityEngine;
using System.Collections;

public class DragAndDrop : MonoBehaviour
{  
    private bool _mouseState;
    private GameObject target;
    public Vector3 screenSpace;
    public Vector3 offset;

    // Use this for initialization
    void Start ()
    {

    }

    // Update is called once per frame
    void Update ()
    {
        // Debug.Log(_mouseState);
        if (Input.GetMouseButtonDown (0)) {

            RaycastHit hitInfo;
            target = GetClickedObject (out hitInfo);
            if (target != null) {
                _mouseState = true;
                screenSpace = Camera.main.WorldToScreenPoint (target.transform.position);
                offset = target.transform.position - Camera.main.ScreenToWorldPoint (new Vector3 (Input.mousePosition.x, Input.mousePosition.y, screenSpace.z));
            }
        }
        if (Input.GetMouseButtonUp (0)) {
            _mouseState = false;
        }
        if (_mouseState) {
            //keep track of the mouse position
            var curScreenSpace = new Vector3 (Input.mousePosition.x, Input.mousePosition.y, screenSpace.z);

            //convert the screen mouse position to world point and adjust with offset
            var curPosition = Camera.main.ScreenToWorldPoint (curScreenSpace) + offset;

            //update the position of the object in the world
            target.transform.position = curPosition;
        }
    }


    GameObject GetClickedObject (out RaycastHit hit)
    {
        GameObject target = null;
        Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
        if (Physics.Raycast (ray.origin, ray.direction * 10, out hit)) {
            target = hit.collider.gameObject;
        }

        return target;
    }
}

Upvotes: 1

Technivorous
Technivorous

Reputation: 1712

in order for your cube to take the OnMouseDown() event you need to add a collider and rigidbody. click the cube, go to the properties on the right and click add component - physics - cube collider then do the same, for the rigid body add component - physics - rigid body.

dont forget to set the rigidbody to kinematic, or set the gravity scale to 0 if you dont want it to fall out of the scene

Upvotes: 2

Related Questions