简体   繁体   中英

Unity - Continuously change the forward direction of game object?

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.

Your question seems a little confusing, but it seems like you want a ball to rotate around a line. The ball to rotate at its own will and the line to just stay relative to the ball and no rotation.

If this is correct. What I suggest is having two objects. the ball and then an empty/invis object. The ball rotates and moves and just takes the empty object with it by movement, no rotation. Put the line renderer on the empty object and in the hierarchy have invis object be the parent of the ball. Move the empty object with the ball physics and bamn rolling ball, that responds to touch.

Sorry, if Im bad at explaining. And if you dont know when you parent something in the hierarchy they move together.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM