Hey, all. I was trying to use the code from the scripting API for Camera.SceneToWorldPoint to make the player look at the mouse. Thing is, it works wonders if the camera is facing straight down, but I need it to work as the camera’s X rotation is at 0 instead of 90. Here’s what I did so far to make it work while looking down, if anyone needs this code.
void OnGUI()
{
Vector3 point = new Vector3();
Event currentEvent = Event.current;
Vector2 mousePos = new Vector2();
// Get the mouse position from Event.
// Note that the y position from Event is inverted.
mousePos.x = currentEvent.mousePosition.x;
mousePos.y = cam.pixelHeight - currentEvent.mousePosition.y;
point = cam.ScreenToWorldPoint(new Vector3(mousePos.x, mousePos.y, cam.nearClipPlane));
GUILayout.BeginArea(new Rect(20, 20, 250, 120));
GUILayout.Label("Screen pixels: " + cam.pixelWidth + ":" + cam.pixelHeight);
GUILayout.Label("Mouse position: " + mousePos);
GUILayout.Label("World position: " + point.ToString("F3"));
GUILayout.EndArea();
transform.LookAt(-point);
}
Nothing I have done to switch the rotations have given me much luck. Please help? Thank you.
Edit: I changed the code, it’s still not perfect. Anyone else notice the issue which is hiding from me? Thanks. I’ll leave the top one in case someone else might need it.
public class MouseLook : MonoBehaviour
{
private Camera cam;
Vector3 point;
public GameObject Laser;
public Transform Aim;
void Start()
{
cam = Camera.main;
}
private void Update()
{
point = cam.ScreenToWorldPoint(Input.mousePosition);
transform.LookAt(new Vector3(-point.x, -point.y, 0));
}
}
I think I just got it.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MouseLook : MonoBehaviour
{
private Camera cam;
Vector3 point;
public GameObject Laser;
public Transform Aim;
void Start()
{
cam = Camera.main;
}
private void Update()
{
point = cam.ScreenToWorldPoint(Input.mousePosition);
transform.LookAt(new Vector3(point.x, point.y, 0));
}
}