- Home /
Simple drag and drop - no physics
I want to simply drag and drop objects without rigidbody or physics. I found a old script of this written in C#. Its not working for me - I get a "NullReferenceException"
Can somebody fix this or convert it into Javascript? Here the code:
using UnityEngine;
using System.Collections;
[RequireComponent(typeof(BoxCollider))]
public class MovePoint2 : MonoBehaviour
{
private Vector3 screenPoint;
private Vector3 offset;
void OnMouseDown()
{
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
Screen.showCursor = false;
}
void OnMouseDrag()
{
Vector3 curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
Vector3 curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
void OnMouseUp()
{
Screen.showCursor = true;
}
}
Here the Error in detail: UnityEngine.Camera.WorldToScreenPoint (Vector3 position) (at C:/BuildAgent/work/842f9557127e852/Runtime/ExportGenerated/Editor/UnityEngineCamera.cs:225) MovePoint2.OnMouseDown () (at Assets/Scripts/General Scripts/MovePoint2.cs:13) UnityEngine.SendMouseEvents:DoSendMouseEvents()
I forgot to tag the camera as "$$anonymous$$ain Camera". Now it does work well. Thanks!
Answer by benfattino · May 14, 2012 at 12:41 PM
Javascript:
private var screenPoint: Vector3;
private var offset: Vector3;
private var curScreenPoint : Vector3;
private var curPosition : Vector3;
function Start () {
}
function Update () {
}
function OnMouseDown () {
screenPoint = Camera.main.WorldToScreenPoint(gameObject.transform.position);
offset = gameObject.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z));
Screen.showCursor = false;
}
function OnMouseDrag() {
curScreenPoint = new Vector3(Input.mousePosition.x, Input.mousePosition.y, screenPoint.z);
curPosition = Camera.main.ScreenToWorldPoint(curScreenPoint) + offset;
transform.position = curPosition;
}
function OnMouseUp(){
Screen.showCursor = true;
}
Tips welcome!
Answer by Mox.du · Nov 19, 2011 at 02:51 AM
Open new scene, make cube, add this script to cube (make sure you name script "MovePoint2" since this is the name of the class).
Answer by dione001 · Nov 13, 2013 at 09:53 AM
What if there is a camera angle?. I want to move to object within the plane only,
Answer by Aarlangdi · Mar 07, 2014 at 03:18 PM
Check this out, this one has shown drop and drop in unity only in few lines of code --- http://aarlangdi.blogspot.com.au
Your answer
Follow this Question
Related Questions
Drag and drop an external file/folder into a running game window? 2 Answers
Drag item on screen once spawned. 0 Answers
How to move UI image between panels 0 Answers
Drag & Drop & Arrange 0 Answers
Drag and Drop Inside Editor 0 Answers