- Home /
Question by
Juancho · Jun 18, 2013 at 10:27 AM ·
addforcetransform.positiononmousedrag
addforce and onmousedrag ?
Hello.. i have a drag and drop code which works but now i discovered that this code updating the transform.position from a raycast doesnt work with collisions and i need that my dragged gameobject collides with the scene.
Is there any way i can move the gamobject with onMouseDrag() and still having collisions? like adding a force in the direction of the mouse movement?
Here is my drag and drop code:
using UnityEngine;
using System.Collections;
public class Gui : MonoBehaviour {
public Transform clone;
public Transform ObjectToPlace;
private GameObject obj;
private Vector3 screenPoint;
private Vector3 offset;
private Vector3 mousePos;
private Ray ray2;
private RaycastHit hit2;
int layerMask2;
public bool dest=false;
private Rect boton1=new Rect(10, 40, 50, 80);
private Rect boton2=new Rect(70, 40, 50, 80);
void OnGUI() {
GUI.BeginGroup(new Rect(0, Screen.height-100, Screen.width, 100));
GUI.Box(new Rect(0, 0, Screen.width, 100),"");
CheckButton(boton1,1);
CheckButton(boton2,2);
GUI.Button(boton1,"");
GUI.Button(boton2,"");
GUI.EndGroup();
}
void CheckButton(Rect boton,int cod) {
switch(cod) {
case 1:obj=(GameObject) Resources.Load("Cube01");break;
case 2:obj=(GameObject) Resources.Load("Cube02");break;
}
ObjectToPlace=obj.transform;
if(boton.Contains(Event.current.mousePosition)) {
if(Input.GetButtonDown("Fire1")) {
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
RaycastHit hit;
var layerMask = 1 << 8;
if (Physics.Raycast (ray, out hit, Mathf.Infinity, layerMask)) {
clone = hit.transform;
}else{
layerMask = ~layerMask;
if (Physics.Raycast (ray, out hit, Mathf.Infinity, layerMask)) {
clone = (Transform) Instantiate(ObjectToPlace, hit.point, Quaternion.identity);
}
}
}
}
if(Input.GetButtonUp("Fire1")) {
if ((!dest)&&(Physics.Raycast(ray2, out hit2, Mathf.Infinity, layerMask2))) {
Destroy(clone.gameObject);
dest=true;
}
clone=null; // clear clone variable
}
if(Input.GetButton("Fire1")) {
if (clone!=null) {
ray2 = Camera.main.ScreenPointToRay (Input.mousePosition);
layerMask2 = 1 << 8;
layerMask2 = ~layerMask2;
if (Physics.Raycast (ray2, out hit2, Mathf.Infinity, layerMask2)) {
clone.position = hit2.point;
}
layerMask2 = 1 << 10;
}
}
}
}
Thank you.
Comment
See the DragRigidbodyScript that comes with Unity. To get it: from the Assets menu select Import Package/Scripts.