Home > Blockchain >  Draw a line from object to where camera is facing in Unity
Draw a line from object to where camera is facing in Unity

Time:09-30

I am starting out to create a minigolf game in Unity. I want to aim by draggin the screen with my mouse which rotates the camera around the ball. Basically I want to draw an aim line (line renderer or any other good method) from the ball to where the camera is pointing. Right now I just draw the line I want from beginning, but in the end I want it to rotate with the camera like the red line in picture below.

enter image description here

The code for rotating the camera is working great, where previousCameraPosition is set when I click the mouse and Rotate() is called when mouse button is being held down:

private void Rotate()
    {
        // Get the movement vector
        Vector3 cameraMoveDirection = previousCameraPosition - mainCamera.ScreenToViewportPoint(Input.mousePosition);

        // Rotate around the ball
        mainCamera.transform.position = ballObject.transform.position;

        // Make the rotations
        mainCamera.transform.Rotate(new Vector3(1, 0, 0), cameraMoveDirection.y * 360);
        mainCamera.transform.Rotate(new Vector3(0, 1, 0), -cameraMoveDirection.x * 360, Space.World);

        // Set the camera a certain amount away from the ball
        mainCamera.transform.Translate(new Vector3(0, 0, -ballObject.transform.position.z*2.5f));

        // Update the previousCameraPosition during the movement
        previousCameraPosition = mainCamera.ScreenToViewportPoint(Input.mousePosition);
    }

I tried to create a helper object which was set to rotate exactly like the camera which made the line exactly like I wanted it, except it was backwards (180 degrees wrong, facing into the camera instead of away) and it was 1 unit long since it was normalized. I am stuck on this for far too long now, any help or guidance would be very appreciated.

CodePudding user response:

First you can simply use the camera's forward vector without having to deal with any Quaternion rotation at all:

var forward = Camera.main.transform.forward;

Then what you actually seem to want is not exactly this direction but rather map it onto a flat XZ plane:

var actualForward = Vector3.ProjectOnPlane(forward, Vector3.up).Normalized;

then finally you can use this direction to draw your line e.g. between the points

var startPoint = ball.position;
var endpoint = startPoint   actualForward * lineLength;
  • Related