Smooth Drag and drop in Unity 3d [ Video ]

Advertisemen

This video will show you guys how do drag and drop an object in unity in a very simple with less amount of codes.



Codes used in the video above. You can copy and paste these codes ---

In C# :

using UnityEngine;
using System.Collections;

public class drag : MonoBehaviour {
    Vector3 dist;
    float posX;
    float posY;

  void OnMouseDown(){
      dist = Camera.main.WorldToScreenPoint(transform.position);
      posX = Input.mousePosition.x - dist.x;
      posY = Input.mousePosition.y - dist.y;

    }

  void OnMouseDrag(){
 
     Vector3 curPos = 
                new Vector3(Input.mousePosition.x - posX
                Input.mousePosition.y - posYdist.z);  

      
Vector3 worldPos = Camera.main.ScreenToWorldPoint(curPos);
      transform.position = worldPos;
    }
}


In Javascript :

#pragma strict
    private var dist : Vector3;
    private var posX : float;
    private var posY : float;

    function OnMouseDown(){
      dist = Camera.main.WorldToScreenPoint(transform.position);
      posX = Input.mousePosition.x dist.x;
      posY = Input.mousePosition.y - dist.y;

    }

    function OnMouseDrag(){
      var curPos = 
new Vector3(Input.mousePosition.x - posX
                     Input.mousePosition.y - posYdist.z);
               
      var worldPos = Camera.main.ScreenToWorldPoint(curPos);
      transform.position = worldPos;
    }

Please don't forget to like, comment, subscribe and share.
Thank u.

Advertisemen

Disclaimer: Gambar, artikel ataupun video yang ada di web ini terkadang berasal dari berbagai sumber media lain. Hak Cipta sepenuhnya dipegang oleh sumber tersebut. Jika ada masalah terkait hal ini, Anda dapat menghubungi kami disini.

Tidak ada komentar:

Posting Komentar

© Copyright 2017 Tutorial Unity 3D