I am trying to make a mouse trail. When you move your mouse, the gameobject with trail renderer will move along with your mouse. So I first got mouse position which is on screenspace. Then I converted it to worldspace. Then I put the converted position onto trail’s position. But it is not working. When I place my mouse on bottom-left corner of screen, only then the trail comes.But it comes at the middle of screen! And if I move mouse by very few pixels, the trail move by large pixels(often out of screen!)
The code I am using is below:
using UnityEngine;
using System.Collections;
public class debugGUIscript : MonoBehaviour
{
public Transform trail;
public Camera camera;
void Update()
{
Matrix4x4 conv=camera.cameraToWorldMatrix;
Vector3 convMousePoint= conv.MultiplyPoint(new Vector3(Input.mousePosition.x,Input.mousePosition.y,0.0f));
trail.transform.position= new Vector3 (convMousePoint.x,convMousePoint.y, 0.0f);
}
}
screen to world method, “Camera.ScreenToWorldPoint”. You are referring this,right? Oh boy, thank you very very much. Now I have got it right. For anyone facing similar situation, The changed code for mouse trail is:
using UnityEngine;
using System.Collections;
public class debugGUIscript : MonoBehaviour
{
public Transform trail;
public Camera camera;
void Update()
{
Vector3 convMSpoint= camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, camera.nearClipPlane));
trail.transform.position= new Vector3(convMSpoint.x,convMSpoint.y,convMSpoint.z);
}
}
There should be a gameObject with which a trail renderer attached. At first,trail might go to a very biger size. So, we should carefully put nice value on “time” “start width” “end width” “min vertex distance”.
I guess we can transform any gameobject into screen by this method,isn’t it? Using “Camera.ScreenToWorldPoint” and “Camera.WorldToScreenPoint” with a second depth enabled camera could lead to a nice GUI system with minimal drawcall.
edit I have successfully converted it for touch too. Here is the code for touch devices.
using UnityEngine;
using System.Collections;
public class debugGUIscript : MonoBehaviour
{
public Transform trail;
public Camera camera;
void Update()
{
foreach (Touch touch in Input.touches)
{
Vector3 convTCpoint= camera.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, camera.nearClipPlane));
trail.transform.position= new Vector3(convTCpoint.x, convTCpoint.y,convTCpoint.z);
}
}
}