- Home /
Homing missile and LookAt issue
Hi, just started with Unity a week ago and right now I'm working on homing/guided missiles for a basic flight combat game.
My issue is that even if I am staring at the target directly, the missiles decide to take a longer round path for some reason.
Code to launch missile (in script attached to plane):
var rocket = Instantiate(rocketPrefab, transform.position, transform.rotation);
var script : missileHomingScript = rocket.GetComponent(missileHomingScript);
script.target = currentTarget;
rocket.rigidbody.AddForce(transform.forward * 2000);
Missile homing code (in script attached to missile):
transform.LookAt(target);
transform.Translate(transform.forward);
Initially I thought it was to do with my plane's rotation, but if I disable the homing code it flies straight (thanks to the initial AddForce
when fired)
Here's a pic to help visualise the situation. What am I doing wrong here?
can you tell me current target is what ? Transform or vector3 ?
Answer by jayw · Apr 09, 2011 at 03:34 AM
The issue is fixed.
Reading up on more about similar situations, I discovered that "you shouldn't mix physics and direct transformations" and that I didn't really need physics for the missiles anyway (so the RigidBody component was removed). Also thanks to this and this, it's all working with the following code edits:
Got rid of the RigidBody, and applied initial rotation for missile to face direction of plane's velocity:
var rocket = Instantiate(rocketPrefab, transform.position, transform.rotation);
var script : missileHomingScript = rocket.GetComponent(missileHomingScript);
script.target = currentTarget;
rocket.transform.rotation = Quaternion.LookRotation(transform.forward); //edited
Used Vector3.forward
instead of transform.forward
:
transform.LookAt(target);
transform.Translate(Vector3.forward * 1); //edited
If anyone else was on the same boat I was and still needed RigidBodies, then I suggest looking at rotations done by RigidBody.AddTorque
.