Creating a Homing Missile in Unity

Published March 05, 2014 by Preet Kamal Minhas, posted by pkMinhas
Do you see issues with this article? Let us know.
Advertisement
Homing missiles have been my favorite in all types of games. There is nothing more fun than a fire & forget weapon. Homing missiles will generally lock on to a target & keep following it till a collision occurs OR the missile might auto-destruct after a certain period of time. This article will talk about creating homing missiles in Unity using a kinematic rigidbody in order to keep things simple. A kinematic rigidbody's transform can be manipulated directly. Also, I would like to introduce you to my game, Hawks, which is a WIP at the moment with 90% of the functionality in place.

A basic homing missile will operate based on three properties: Speed, Auto Destruct time & target.

Important: The following code should be attached to a gameobject having a Rigidbody component with isKinematic set to true.
  1. Speed: Since we are using a kinematic rigidbody, the speed of the projectile can be controlled by translating in the Update() function:

    transform.Translate(0,0,speed * Time.deltaTime,Space.Self);
  2. Auto Destruct: This functionality can be implemented by calling a coroutine which self-destructs after a set amount of time:

    function Start () { StartCoroutine(AutoExplode()); } private function ExplodeSelf() { Instantiate(explosion,transform.position,Quaternion.identity); Destroy(gameObject); } private function AutoExplode() { yield WaitForSeconds(autoDestroyAfter); ExplodeSelf(); }
  3. Target: The missile needs to follow the target. We can achieve this by rotating the missile towards the target transform using the wonderful Slerp function:

    var relativePos : Vector3 = target.position - transform.position; var rotation : Quaternion = Quaternion.LookRotation(relativePos); transform.rotation = Quaternion.Slerp(transform.rotation, rotation, homingSensitivity);
Notice the homingSensitivity variable that is used as the last parameter to the Quaternion.Slerp(from, to, t) function. To understand its usage, we need to look at what the Slerp actually does. Slerp == Spherical Interpolation. Mathematical details available at: http://en.wikipedia.org/wiki/Slerp. For those not so mathematically inclined, given two values, the Slerp function will calculate an intermediate position between from & to based on the third parameter which lies in the range [0,1]. If the third param is 0, the from value will be returned & 1 will return the to value. Try experimenting with different values to achieve the desired effect in your game. Below is the complete code for the HomingMissile.js script: #pragma strict var target : Transform; var speed : float; var autoDestroyAfter : float; //prefab for explosion var explosion : GameObject; /* Represents the homing sensitivity of the missile. Range [0.0,1.0] where 0 will disable homing and 1 will make it follow the target like crazy. This param is fed into the Slerp (defines the interpolation point to pick) */ var homingSensitivity : float = 0.1; function Start () { StartCoroutine(AutoExplode()); } function Update () { if(target != null) { var relativePos : Vector3 = target.position - transform.position; var rotation : Quaternion = Quaternion.LookRotation(relativePos); transform.rotation = Quaternion.Slerp(transform.rotation, rotation, homingSensitivity); } transform.Translate(0,0,speed * Time.deltaTime,Space.Self); } function OnTriggerEnter(other: Collider) { //Damage the other gameobject & then destroy self ExplodeSelf(); } private function ExplodeSelf() { Instantiate(explosion,transform.position,Quaternion.identity); Destroy(gameObject); } private function AutoExplode() { yield WaitForSeconds(autoDestroyAfter); ExplodeSelf(); }

Hawks: Guardians of the Skies

I began development on Hawks around 6 months back. The game has come a long way since then & I would like to give back to the community with more articles & insights into the game dev process. Check out Hawks on IndieDB

Article Update Log

28 Feb 2014: Initial release
Cancel Save
-1 Likes 11 Comments

Comments

fafase

Well this applies to anything meant to move towards a target, here http://unitygems.com/basic-ai-character/ I apply the same principle to a character moving either towards a waypoint or towards the player.

Also, you should add the fact that at fast speed, you may miss collision and then should add a raycast system to make sure your rocket is not one frame on one side of the wall and next frame on the other side.

You mention the homingSensitivity should be within 0 and 1, why not adding an attribute to make sure?

At 1 it won't follow the target like crazy it will hit instantly regardless of any obstacles, so you may want to prevent that value as well.

What is set to IsTrigger? The rocket collider?

You should also tell to check for what is colliding, if you have an invisible trigger box meant to be used for level design like a waypoint, then your rocket will explode for no reason (at least to the player).

March 06, 2014 03:12 PM
pkMinhas

Well this applies to anything meant to move towards a target, here http://unitygems.com/basic-ai-character/ I apply the same principle to a character moving either towards a waypoint or towards the player.

Also, you should add the fact that at fast speed, you may miss collision and then should add a raycast system to make sure your rocket is not one frame on one side of the wall and next frame on the other side.

You mention the homingSensitivity should be within 0 and 1, why not adding an attribute to make sure?

At 1 it won't follow the target like crazy it will hit instantly regardless of any obstacles, so you may want to prevent that value as well.

What is set to IsTrigger? The rocket collider?

You should also tell to check for what is colliding, if you have an invisible trigger box meant to be used for level design like a waypoint, then your rocket will explode for no reason (at least to the player).

I would like to address your points one by one:

"At fast speed you may miss collision". This can be mitigated by setting the appropriate collision detection mode for the rigidbody: https://docs.unity3d.com/Documentation/ScriptReference/Rigidbody-collisionDetectionMode.html

"Homing sensitivity 0,1..." The homing sensitivity is used to control the rotation & not the position. Hence, setting it to 0,1 will change the rotation & not the position. It is safe to set it to 1 in this script. Try it out.

This value is already exposed in the inspector since it is a public attribute. (Check the complete code at the end of the article)

"OnTriggerEnter" This part can be elaborated further. I will update it along with one of my upcoming articles which talks about trigger based collision detection.

March 06, 2014 03:35 PM
Jet Set Willy

It would be better to teach new games programmers the basics of things like motion in a more general way. This tutorial just adds to the huge list of tutorials (usually written to gather ad revenue) where people can copy the code they need without understanding what they're doing, producing developers that make shoddy games by copy and pasting tutorials and getting stuck at every point where they might have to solve a problem.

There's no explanation of why anything is done, or how it works in more general cases. People will learn how to copy and paste your code into their project and nothing else.

Another one for the "sir what are the codes plz" crowd.

March 06, 2014 03:55 PM
pkMinhas

It would be better to teach new games programmers the basics of things like motion in a more general way. This tutorial just adds to the huge list of tutorials (usually written to gather ad revenue) where people can copy the code they need without understanding what they're doing, producing developers that make shoddy games by copy and pasting tutorials and getting stuck at every point where they might have to solve a problem.

There's no explanation of why anything is done, or how it works in more general cases. People will learn how to copy and paste your code into their project and nothing else.

Another one for the "sir what are the codes plz" crowd.

I appreciate your point of view. However, this article was not meant to explain the basics to beginners. This is more of a hands on article with a clear purpose of teaching a certain kind of technique.

March 06, 2014 04:11 PM
fafase

Hei,

homingSensitivity case is solved, I was wrong on that one.

Concerning the collision detection, setting to continuous dynamic I think Unity used to tell it will help but not solve the issue on every case.

March 06, 2014 04:42 PM
bratiefanut

It would be better to teach new games programmers the basics of things like motion in a more general way. This tutorial just adds to the huge list of tutorials (usually written to gather ad revenue) where people can copy the code they need without understanding what they're doing, producing developers that make shoddy games by copy and pasting tutorials and getting stuck at every point where they might have to solve a problem.

There's no explanation of why anything is done, or how it works in more general cases. People will learn how to copy and paste your code into their project and nothing else.

Another one for the "sir what are the codes plz" crowd.

Just logged in to up vote you sir.

March 06, 2014 04:47 PM
ProtectedMode

I'm sorry, but I have a few negative points:

  • This code is really specific, as said it could be more general.
  • The code is trivial to write for somebody with reasonable programming experience and/or access to other tutorials.
  • The biggest point: this article feels like advertisement to me. You have a hole heading dedicated to your game, even though it doesn't have much content, while I don't really see any relationship aside from what you mentioned.

The article is however practical and may be useful. But maybe try to put more content in it next time. ;)

Edit: why is my mark-up not saved?

March 06, 2014 11:41 PM
Tutorial Doctor
I'm so dumb haha. I was making my own vector3 function, and forgot there is one built into the engine I am using. Thanks for this! The process will come in handy, and I might be able to use it for my AI script. Nice simple code too.
March 07, 2014 05:09 AM
brunopava

I would also add a RayCast on the tip of it to check if it is about to collide with something and then auto destroy it on act.

Lets say the player uses an obstacle to block the incoming missile.

The translate function ignores colliders, so the missile would be passing through walls and etc.

March 07, 2014 03:38 PM
pkMinhas

I would also add a RayCast on the tip of it to check if it is about to collide with something and then auto destroy it on act.

Lets say the player uses an obstacle to block the incoming missile.

The translate function ignores colliders, so the missile would be passing through walls and etc.

This can be accomplished using various techniques. Raycasting is one.

For my current game, I attach a specific script to objects which can take damage/ act as obstacles. OnTriggerEnter, check whether the other game object has this script. If yes, call the method which reduces other's health & then ExplodeSelf().

March 08, 2014 04:25 AM
jefferytitan

Firstly, I'd like to say that I value contributions. I'm sure there are people that could get value from that script.

In my opinion articles should either have some general applicability to the reader's game development abilities, or go deeply into an esoteric topic. The scope of this article seems quite narrow, and largely consists of the code itself.

I feel that either this could be part of an article on a related set of technologies from your game, or may be better suited to one of the variety of sites devoted to short unity scripts.

July 30, 2014 02:51 AM
You must log in to join the conversation.
Don't have a GameDev.net account? Sign up!

This article is intended towards developers who are using Unity for their game.

Advertisement

Other Tutorials by pkMinhas

pkMinhas has not posted any other tutorials. Encourage them to write more!
Advertisement