Hi all
Have a Nice day. In my project I have a 3d Object .for eg sphere. When i touch the object the object should
move. I have found the code for that. I have enclose with the code.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DragDropScript : MonoBehaviour
{
//Initialize Variables
GameObject getTarget;
bool isMouseDragging;
Vector3 offsetValue;
Vector3 positionOfScreen;
// Use this for initialization
void Start()
{
}
void Update()
{
//Mouse Button Press Down
if (Input.GetMouseButtonDown(0))
{
RaycastHit hitInfo;
getTarget = ReturnClickedObject(out hitInfo);
if (getTarget != null)
{
isMouseDragging = true;
//Converting world position to screen position.
positionOfScreen = Camera.main.WorldToScreenPoint(getTarget.transform.position);
offsetValue = getTarget.transform.position - Camera.main.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, positionOfScreen.z));
}
}
//Mouse Button Up
if (Input.GetMouseButtonUp(0))
{
isMouseDragging = false;
}
//Is mouse Moving
if (isMouseDragging)
{
//tracking mouse position.
Vector3 currentScreenSpace = new Vector3(Input.mousePosition.x, Input.mousePosition.y, positionOfScreen.z);
//converting screen position to world position with offset changes.
Vector3 currentPosition = Camera.main.ScreenToWorldPoint(currentScreenSpace) + offsetValue;
//It will update target gameobject's current postion.
getTarget.transform.position = currentPosition;
}
}
//Method to Return Clicked Object
GameObject ReturnClickedObject(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;
}
}
But the Object moves on where i touch the finger.But it should go on the terrain . Like in the Edit View
after selecting the object if
we press ctrl+shift. the object is moving on the terrain . Like similar functionality
is needed for me.In touch.
How can i do it…
Any help … Appreciated…
Thanks in Advance…