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 - posY, dist.z);
Vector3 worldPos = Camera.main.ScreenToWorldPoint(curPos);
transform.position = worldPos;
}
}
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 - posY, dist.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 - posY, dist.z);
var worldPos = Camera.main.ScreenToWorldPoint(curPos);
transform.position = worldPos;
}
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 - posY, dist.z);
var worldPos = Camera.main.ScreenToWorldPoint(curPos);
transform.position = worldPos;
}
Please don't forget to like, comment, subscribe and share.
Thank u.
Advertisemen
Tidak ada komentar:
Posting Komentar