The barrel faces straight up and changes shape when I hit play. I had to attach the script to the camera because when I attached it to the turret with some changes, it said that there was no camera when it looked for the camera. I am thoroughly confused and would appreciate some help. PS it is a topdown shooter.
here is the code:
using UnityEngine;
using System.Collections;
public class TurretLook : MonoBehaviour
{
public Transform turret;
// Use this for initialization
void Start ()
{
}
// Update is called once per frame
void Update ()
{
Vector3 mouselocation = camera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Screen.height - Input.mousePosition.y, camera.nearClipPlane));
//look at mouse
turret.LookAt(mouselocation);
}
}
I don’t know that there’s enough information there to say what’s wrong, but here’s a guess. If the object is intended to rotate in the XY plane, you may need to specify a different reference vector for LookAt(), e.g.:
I think your problem stems from the use of the nearClipPlane as a parameter in the ScreenToWorldPoint. the new clip plane is normally very close to your camera object (Hence the name) I would have thought you would need instead use the distance between the turret and the camera.
Alternatively you could use a physics raycast in to the scene at the mouse,x / y position and then use the hit location for the turret look at.
var ray = Camera.main.ScreenPointToRay (Input.mousePosition);
var hit : RaycastHit;
if (Physics.Raycast (ray, hit, 100)) {
turret.LookAt(hit.point);
}
regarding the issue you have with your camera… You really need to fix that so you can attach the script to multiple turrets. Use GameObject.Find to find your camera or if your using a single camera titled MainCamera you can use the camera.Main to return the main camera reference.