I have a simple look at mouse cursor script that I’m trying to use to aim a turret by rotating on the Z-axis. Except I’m having some troubles with getting it to rotate correctly. Here is the script:
using UnityEngine;
using System.Collections;
public class LookAtMouse : MonoBehaviour {
public float speed;
void FixedUpdate ()
{
Plane playerPlane = new Plane(Vector3.up, transform.position);
Ray ray = Camera.main.ScreenPointToRay (Input.mousePosition);
float hitdist = 0.0f;
if (playerPlane.Raycast (ray, out hitdist))
{
Vector3 targetPoint = ray.GetPoint(hitdist);
targetPoint.z = 0;
Quaternion targetRotation = Quaternion.LookRotation(targetPoint - transform.position);
transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, speed * Time.time);
}
}
}
The turret is just a simple place holder I made in Blender- one horizontal cylinder with two barrels attached pointing up. The purpose of the script is to make the barrels aim at the mouse cursor while only rotating on the Z-axis. I can’t get that to happen no matter how I change the transform position of the plane.
I could be wrong, shouldn’t Vector3.up tell the cylinder to look a long the Y-axis? That is the direction that my barrels are pointing and shouldn’t setting targetPoint.z = 0 lock rotation to the Z-axis? I think the problem is with the transition from Blender to Unity- from Z-up to Y-up, as the cylinder rotates but the barrels are never looking at the mouse.