I'm creating a project in which I have a sphere GameObject which has empty game object as a child. A line renderer component is attached to the this empty game object.
I have made the sphere to look at the touch direction so that the line renderer of the child object also faces towards the touch position. It works fine when the sphere is rotating in one axis.
But the problem occurs when I apply a force to the sphere and it starts rotating in all axis just like a normal ball. But the line renderer attached to it is stuck to its face and when the sphere faces downwards, the line renderer goes into the ground.
Code for Line Renderer.
using UnityEngine;
using System.Collections;
public class LineRenderer : MonoBehaviour {
private LineRenderer lineRenderer;
private Vector3 finalTouchPosition;
// Use this for initialization
void Start () {
lineRenderer = gameObject.GetComponent<LineRenderer> ();
}
// Update is called once per frame
void Update () {
Ray ray = new Ray (transform.position, transform.forward);
RaycastHit hit;
lineRenderer.SetPosition (0, ray.origin);
if (Physics.Raycast (ray, out hit)) {
lineRenderer.SetPosition (1, hit.point);
}
}
}
Code for rotating the object with touch.
if(theTouch.phase == TouchPhase.Moved)
{
Vector3 tempTouch = new Vector3(theTouch.position.x ,theTouch.position.y, myCamera.position.y - targetObject.transform.position.y);
fingerPosition = Camera.main.ScreenToWorldPoint(tempTouch);
targetObject.transform.LookAt(fingerPosition);
isRotating = true;
}
I want the line renderer to always be parallel to the ground but originate from the sphere or face of the sphere. I've tried many things. But still haven't found the solution.