I have a box in Unity that I want to turn to face in a direction. I tried to use Transform.lookAt() and Transform.rotation but neither seem to work. Here are my code examples for both lookAt and rotation.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
float mouseX;
float mouseY;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = true;
}
// Update is called once per frame
void Update()
{
mouseX = Input.GetAxis("Mouse X");
mouseY = Input.GetAxis("Mouse Y");
Vector3 mousePosition = new Vector3(mouseX, mouseY, transform.rotation.z);
transform.rotation = new Quaternion(0, 0, mouseX-mouseY, 0);
}
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Move : MonoBehaviour
{
float mouseX;
float mouseY;
// Start is called before the first frame update
void Start()
{
Cursor.lockState = CursorLockMode.Locked;
Cursor.visible = true;
}
// Update is called once per frame
void Update()
{
mouseX = Input.GetAxis("Mouse X");
mouseY = Input.GetAxis("Mouse Y");
Vector3 mousePosition = new Vector3(mouseX, mouseY, transform.rotation.z);
transform.LookAt(mousePosition, Vector3.forward);
}
}
Here is what the scene looks like in unity

I am trying to make the cube turn on the z axis towards the mouse pointer and then move towards it.