rotating an object to look at a point created by a raycast from the main camera onto a 3D sphere

Hi there.
I am trying to use a raycast from the main camera in my scene to the mouse cursor point then using the vector 3 from this cast to create a direction from a missile object to the vector3 created. The object seems to be rotating towards this point but only on two axis so it never fly’s down towards the point and merely circles it at a certain distance above the ground! Here is the code I am using:

var missileSpeedMax: int = 40;
var missileSpeed: int = 0;
var initProcedureActive: boolean = true;
var Target;
var leftRot90;
var hit: RaycastHit;
var clickPos: Vector3;
var initTimerEnd: boolean = false;
var point : Vector3;

function Start () {
	missileSpeed = 1;
	if (Physics.Raycast(Camera.main.ScreenPointToRay(Input.mousePosition),hit, 1000))
      	clickPos = hit.point;

function InitTimer() {
	yield WaitForSeconds(0.2);
	initTimerEnd = true;

function Update () {
	leftRot90 = Quaternion.Euler(transform.localRotation.x,transform.localRotation.y - 90,transform.localRotation.z);
	var rotationLookAt = Quaternion.LookRotation(transform.position, hit.point);
	if (missileSpeed <= missileSpeedMax)
		missileSpeed += 1;
	if (initTimerEnd == true)
		transform.rotation = Quaternion.Slerp(transform.rotation, rotationLookAt, Time.deltaTime * 10); 
	transform.Translate(Vector3.up * Time.deltaTime * missileSpeed);


I suspect the coordinates are not being properly converted from 2d to 3d space. Can anyone help with this?

You have a couple of issues here. First on line 29, you are directly accessing the x,y & z components of localRotation. ‘localRotation’ is a Quaternion, a 4D construct with non-intuitive values. You don’t want to directly access these components unless you have a firm handle on the math behind Quaternions.

The second is the possible issue @Joyrider mentions. You are translating on the Vector3.up vector. This will only work if you get your rotation to point the up in the direction of the target.

The least painful way of dealing with kind of setup is to have the head of your missile pointed towards positive ‘Z’ when the rotation is (0,0,0). If that is not how your misslie is setup, you can:

  • Reauthor the missile in a 3D editing program.
  • Use an empty game object as a parent with the visible missile as a child. You would rotate the missle so that when the child is at (0,0,0), the missile faces forward.
  • Multiply look rotation by a Quaternion at the end to correct the rotation.

The typical code to do what you want would be:

var rotationLookAt = Quaternion.LookRotation(hit.point - transform.position);
 transform.rotation = Quaternion.Slerp(transform.rotation, rotationLookAt, Time.deltaTime * 10); 

And your movement code:

transform.Translate(Vector3.forward * Time.deltaTime * missileSpeed);