I’m trying to make a turret that only rotates on the Z-axis, and faces the target object(in this case the mouse pointer) with the Y-axis. Anyone able to help me?
This is what I have so far, I modified the script from a youtube tutorial called “Top-down shooter”, which originally rotating at the Y-Axis to face with the Z-Axis.
using UnityEngine;
using System.Collections;
public class PlayerTurret : MonoBehaviour {
public Weapon onTurret;
public Camera cam;
public Quaternion targetRotation;
public float rotationSpeed;
public float maxOffSet;
public float minOffSet;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
cam = Camera.main;
MouseControl ();
if(transform.rotation.z > maxOffSet){
transform.rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y, maxOffSet);
}
if(transform.rotation.z < minOffSet){
transform.rotation = Quaternion.Euler(transform.rotation.x, transform.rotation.y, minOffSet);
}
}
void MouseControl(){
Vector3 mousePos = Input.mousePosition;
mousePos = cam.ScreenToWorldPoint(new Vector3(mousePos.x,mousePos.y,cam.transform.position.y - transform.position.y));
targetRotation = Quaternion.LookRotation(mousePos - new Vector3(transform.position.x,transform.position.y, 0));
transform.eulerAngles = Vector3.up * Mathf.MoveTowardsAngle (transform.eulerAngles.z, targetRotation.eulerAngles.z, rotationSpeed * Time.deltaTime);
}
}
Apperently this addaptation is not working correctly, if I rotate the object holding this Turret the turret will keep it’s local rotation and not the parent’s rotation. Anyone able to provide a solution?