Raycast and transform.lookat not working C#

Hello. I’m trying to create a tank, with a turret that will rotate 360. I want the gun and turret to point towards whatever collider is at the center of the camera.

using UnityEngine;
using System.Collections;

public class TurretRotation : MonoBehaviour {

public Camera PlayerCamera;

void Update () {
RaycastHit hit;
Ray ray = Camera.main.ViewportPointToRay (new Vector3 (0.5f, 0.5f, 0f));
if (Physics.Raycast (ray, out hit)) {
transform.LookAt(hit.point);
}
}
}

That is what I have for the raycast and the transform.lookat. The problem is that it will look 90 degrees left of what the camera is looking at, no matter which way the camera is facing. Screenshots:
https://www.dropbox.com/s/grsnb8pcoy8lsi2/New Bitmap Image.bmp?dl=0
https://www.dropbox.com/s/mtry6v2y637b72d/New Bitmap Image (2).bmp?dl=0

Try using Quaternion instead:

transform.rotation = Quaternion.LookRotation(new Vector3(0.5f,0.5f,0.5f)) * Quaternion.Euler(-90, 0, 0);

Adjust the Euler if still wrong angel.

If it is offset by 90 degrees, your model’s forward axis is offset by exactly those 90 degrees. You may directly resolve that within the game object or as mentioned by Ironmax, multiply the rotation by a 90 degrees rotation, though it should look like that in my opinion (WARNING UNTESTED CODE):

Vector3 direction = hit.point - transform.position;
Quaternion offset = Quaternion.Euler (-90, 0, 0);
transform.rotation = Quaternion.LookRotation (direction) * offset;

What this code does is to calculate the look at rotation “manually” and then multiply it with the required offset.
You can certainly compact it into one line. The offset might be wrong, as it can be +/-90 degrees in any direction. You need to find that out on your own.

Edit: Please use code tags to make your code more readable in the forum:
http://forum.unity3d.com/threads/using-code-tags-properly.143875/

Sorry about the code! The code worked. Thanks both of you for you’re reply, it’s really appreciated!

No problem hope it helped :slight_smile: have a good one.