- Home /
Question by
unity_oEVKDotJO50MrQ · Oct 25, 2018 at 04:02 PM ·
canvasmovetouchscreenworld space
Unity - Move Canvas as a 3D GameObject
I have a script with which i can move (on 2 axis) any 3D objects, the script i'm using is this (for mouse and touchscreen)
using UnityEngine;
public class DragInput : MonoBehaviour {
GameObject gObj = null;
Plane objPlane;
Vector3 mO;
Camera cam;
void Awake() {
cam = GameObject.FindGameObjectWithTag("MyCamera").GetComponent<Camera>();
}
Ray GenerateMouseRay()
{
Vector3 mousePosFar = new Vector3(Input.mousePosition.x,Input.mousePosition.y,cam.farClipPlane);
Vector3 mousePosNear = new Vector3(Input.mousePosition.x,Input.mousePosition.y,cam.nearClipPlane);
Vector3 mousePosF = cam.ScreenToWorldPoint(mousePosFar);
Vector3 mousePosN = cam.ScreenToWorldPoint(mousePosNear);
Ray mr = new Ray(mousePosN, mousePosF-mousePosN);
return mr;
}
// Update is called once per frame
void Update ()
{
if(Input.GetMouseButtonDown(0))
{
Ray mouseRay = GenerateMouseRay();
RaycastHit hit;
if (Physics.Raycast(mouseRay.origin, mouseRay.direction, out hit))
{
gObj = hit.transform.gameObject;
objPlane = new Plane(cam.transform.forward*-1, gObj.transform.position);
//calc mouse offset
Ray mRay = cam.ScreenPointToRay(Input.mousePosition);
float rayDistance;
objPlane.Raycast(mRay, out rayDistance);
mO = gObj.transform.position - mRay.GetPoint(rayDistance);
}
}
else if(Input.GetMouseButton(0) && gObj)
{
Ray mRay = cam.ScreenPointToRay(Input.mousePosition);
float rayDistance;
if (objPlane.Raycast(mRay, out rayDistance))
gObj.transform.position = mRay.GetPoint(rayDistance) + mO;
}
else if (Input.GetMouseButtonUp(0) && gObj)
{
gObj = null;
}
}
}
If i click on any object i have created (with a box collider) i can freely move this object over the screen. Unfortunately this will not happen if the object is a World Space UI(canvas). Anyone can gime me some hint and tell me why i'm not able to move the space UI?
Comment
Check the "Render $$anonymous$$ode" setting of the canvas component itself. Is it set to "screen space overlay", or "screen-space camera"? For your purposes, it sounds like you want it configured to use the "worldspace" option
Render $$anonymous$$ode is already set as World Space
Your answer
![](https://koobas.hobune.stream/wayback/20220612180938im_/https://answers.unity.com/themes/thub/images/avi.jpg)