Jump to content
  • Advertisement
Sign in to follow this  
  • entry
    1
  • comments
    0
  • views
    195

About this blog

6691create-homing-missiles-in-game-unity

Objective

The main objective of this post is to give a brief introduction to Homing Missiles in Game (2D). A script for Homing missile is also included and explained in the article.

 

What is a Homing Missile?

What is the logic behind Homing Missiles?

How to use Homing Missiles in Unity?

Have these Questions in Your Mind?

No worries. You will get a satisfactory answer to all those questions, right here.

Let’s start with Introduction

INTRODUCTION

You might have seen Homing Missiles in movies.

real-life-exsmple-homing-missile.thumb.png.838ac260b0837927b9bab93a3d23f327.png

Remembered these scenes from “Marvel’s The Avengers” movie?

If you are not a Marvel fan don’t worry, I am here to help.

Homing Missile is the missile which locks target and chases the target until or unless it reaches the target and blasts itself.

There are plenty of games which are using Homing Missiles.

Excited to implement Homing Missiles in your game?

I know you are.

Let’s set the scene first

Scene Setup:

  1. Create two 2D Objects name them “Missile ” and “Target”.
  2. Add a Sprite to them. (You can download the project from below link).
  3. Add rigidBody 2D in missile and add Script also name it as ”Homing Missile”

How it actually works?

You might think It is easy to Implement Homing Missile. Just use MoveToward/Lerp until it reaches the target.

Just write code and look at what is going on in your scene.(First try and then read further to understand)

working-of-homing-missile.thumb.png.0d333e882691d4a7487a4d49880ae1e4.png

It is reaching the target properly but there is no feel of a rocket. (Right Brain:-What is wrong with my code!)

Below is an actual script for Homing Missiles.

Scripting:

    public class HomingMissile : MonoBehaviour
    {
        public Transform target;
        public Rigidbody2D rigidBody;
        public float angleChangingSpeed;
        public float movementSpeed;
        void FixedUpdate ()
        {
            Vector2 direction = (Vector2)target.position - rb.position;
            direction.Normalize ();
            float rotateAmount = Vector3.Cross (direction, transform.up).z;
            rigidBody.angularVelocity = -angleChangingSpeed * rotateAmount;
            rigidBody.velocity = transform.up * movementSpeed;
        }
    }

I think script is short but not a sweet one. You can use this homing missile script for your code.

Don’t be scared, I’ll show you how to do it.

Let’s start with the table to introduce variables:

  • rigidBody -> rigidBody of the missile to add velocity and change angle.
  • target -> To get the position of the Target.
  • angleChangingSpeed -> The speed to change the angle
  • movementSpeed -> Speed of movement

Pure Mathematics: (Open your Brain’s left part)

actual-path-of-homing-missile.png.7cb21dcd7b272f8b0d76093a336b83c6.png

You need to understand this Picture. That’s How our Homing Missile Works.

First, what you need is “Direction”.

STEP: 1

direction= targetPosition (target.position) - missilePosition(rb.position);

vector-substraction.png.1c8b1fd2c8ec0837710a652d869adcff.png

This is how subtraction of two Vector happens (Pythagoras Theorem).

STEP: 2

direction.Normalize();

Normalization means converting vector to unit vector.

Example:

Vector A(3,4)
Normalized(A)=(3/3*3+4*4 , 4/3*3+4*4)=(3/5,4/5)

STEP: 3

Find Amount of rotation to do that.

float rotateAmount=Vector3.Cross(direction,transform.up).z;

vector-cross-product.gif

Blue Arrow(direction)

Red Arrow(Missile Transform)

green(Resulting Vector).

All three Vectors are perpendicular to each other.that’s why we needed z-axis only.

STEP: 4

Now we need to change angularVelocity of our rigidBody.

rb.angularVelocity = - angleChangingSpeed * rotationAmount.

Minus Sign(-) is used to reverse the direction of movement.

STEP: 5

Adding Velocity to our rigidBody.(just changing the Angle is not Enough).

rb.velocity=tranform.up * movementSpeed

Stop cheering just yet! This is not the end! Missile needs balancing between angleChangingSpeed and movementSpeed.

What if there is no balance between angleChangingSpeed and movementSpeed (Great question! Open right brain is needed here ! )

missile-heading-to-the-target.png.0e57cdc81fd2267a974ad1b78df9c283.png

In the above Image , the missile is heading forward to the target, there is no problem here.

velocity-force-vs-angular-velocity.png.0daafa2818fbe37ff50b079dc7b3e854.png

In the above Image, the target has moved to a new position. The missile continues to go toward the target due to angular velocity (in red) , while still going to the place where the target used to be (in black) due to its velocity. (Thinking what is wrong.?)

velocity-force-vs-angular-velocity-2.png.6de28c58312f7302b6a5cc38fd6979cd.png

In the above Image, the missile's velocity forces it to move at the side of the target (black) while the angular velocity tries to pull the missile to the target. (Now you might feel there is something suspicious).

orbit-dead-loop.png.1b6000ad44ab9086c6fb4b9fa2570bdd.png

In the above Image, the missile falls into a stable orbit around the target and never reaches its goal.

The black arrows indicate a velocity vector while the red lines indicates angular velocity. (That’s why need a balance between angleChangingSpeed and velocity).

Considering that there is no friction in space, there is nothing to slow the velocity of the missile down and collapse the orbit.

That is how whole Universe is trapped (Thank God for this error else there is no life!).

Now, How to Fix this Problem ?

Well, There is no particular formula to balance them, but by Increasing angle or decreasing velocity will help you there.

Caution

  • Don’t go with very small speed so your missile loses the feel of Homing Missile and Don’t make it Extreme fast it will be trapped in the orbit.
  • Don’t make angleChangingSpeed too small else it will fall in to trap and to high angleChangingSpeed loses the feel of your game.

That’s It for Homing Missile. Hoping to see homing Missiles in your game!

Please, do Share our blogs with others if you like our content :)

Originally published at TheAppGuruz - Mobile Game Development Company on May 31, 2018.

Entries in this blog

 

Unity Wheel Collider for Motor vehicle Tutorial 2018

Objective The main objective of this post is to give an idea of how to work with wheel collider and physics of Wheel Collider. Want to Make a Car Racing Game? Having troubles with Car Physics? Where to use Wheel Collider? How to use Wheel Collider? What are the components of Wheel Collider? How is Wheel Collider Different than other Colliders? Have these Questions in Your Mind? No worries... You'll know everything about Wheelcollider after reading this post. INTRODUCTION Wheel Collider is a special kind of Collider which is used for vehicles. It has in built collision detection technique and physics of actual Wheel. It can be used for objects other than wheels (like bumper Boats, bumper cars etc which uses suspension force ), but it is specially designed for vehicles with wheels. Is there is anything special which is not in other Colliders? Yes, each and every collider has something special (That’s why Unity created them). In this Collider, you will get all the components which are used to make vehicle drivable. Do have any idea about components..? No problem, I will explain components here. Before that, it's very important to understand how the Wheel Collider component works internally, to get a car working in Unity Here, I have explained everything. This is how you look at your dashing and shiny car. But, Unity doesn’t have good eyesight. So Unity looks at your car like this. 4 wheels colliders and 1 car collider, that’s it! Now Let’s Discover inside Wheel Collider. Wheel doesn’t have any shape it is Raycast based. Mass & Radius: mass and radius of the wheel. (Easy isn’t it ?) Below I had given a little introduction about physics of wheel collider. Every Wheel counts it’s sprung mass. Sprung mass (not weight) is used to apply individual force on each wheel. Suspension Distance is the distance between max droop and max compression. This suspension is calculated based on rest pose. Suspension Force(F) = (sprungMass * g ) +( jounce * stiffness) - (damper * jounceSpeed) jounce -> offset of the wheel relative to the rest pose. stiffness -> that means physics friction. (setting this to 0 means no friction change this runtime to simulate in various ground material). damper -> damping value applied to the wheel jounceSpeed -> wheel moved with suspension travel direction. Tire simulation rather than using dynamic or static material slip-based material is used. To learn more about physics of wheel collider click here First we need to setup Scene for that (Don’t Worry that is Easy part). PART-1: SCENE SETUP Step 1: Create a 3D plane Object give it scale of (100, 0, 100). Step 2: Create an empty Object add Rigidbody 3D. Name it as “Car” Step 3: Import 3D Car Model inside your Scene (you will get download link below) add as a child of Car. Step 4: Take Mesh Collider and add as a child of Car name it ”CarCollider”. Step 5: Create Two empty GameObject inside Car name them as “Wheel Meshed ” and “Wheel Collider”. Step 6: Inside Wheel Meshes add 4 empty GameObject name them as “FL” ,”FR” ,”RL” and “RR”. assign Mesh of Wheel (you will get download link below). Set their Position. Step 7: Inside Wheel Collider add 4 empty GameObjects name them as “Col_FL” ,”Col_FR”, ”Col_RL” and “Col_RR”. Add wheel collider as their component. Set radius of colliders same as the size of mesh and set their position same as the mesh have. Yeap, Its Done! actually that was the Difficult part to setup scene. Now Time for really easy part Scripting. PART-2: SCRIPTING (Check Script Reference Click here) [System.Serializable] public class AxleInfo { public WheelCollider leftWheelCollider; public WheelCollider rightWheelCollider; public GameObject leftWheelMesh; public GameObject rightWheelMesh; public bool motor; public bool steering; } In this AxleInfo Class, we are going to store info for a pair of the wheel. Variable Name Variable Type Description leftWheelCollider / rightWheelCollider WheelCollider To drive a car using WheelColliders inbuilt physics. leftWheelMesh / rightWheelMesh GameObject To Visualize rotation and movement of wheels. motor bool Enable movement of this pair of wheels. steering bool Enable rotation of this pair of wheels. Now, Let's go for long drive . This script is to drive Car. public class CarDriver : MonoBehaviour { public List<AxleInfo> axleInfos; public float maxMotorTorque; public float maxSteeringAngle; public float brakeTorque; public float decelerationForce; public void ApplyLocalPositionToVisuals (AxleInfo axleInfo) { Vector3 position; Quaternion rotation; axleInfo.leftWheelCollider.GetWorldPose (out position, out rotation); axleInfo.leftWheelMesh.transform.position = position; axleInfo.leftWheelMesh.transform.rotation = rotation; axleInfo.rightWheelCollider.GetWorldPose (out position, out rotation); axleInfo.rightWheelMesh.transform.position = position; axleInfo.rightWheelMesh.transform.rotation = rotation; } void FixedUpdate () { float motor = maxMotorTorque * Input.GetAxis ("Vertical"); float steering = maxSteeringAngle * Input.GetAxis ("Horizontal"); for (int i = 0; i < axleInfos.Count; i++) { if (axleInfos [i].steering) { Steering (axleInfos [i], steering); } if (axleInfos [i].motor) { Acceleration (axleInfos [i], motor); } if (Input.GetKey (KeyCode.Space)) { Brake (axleInfos [i]); } ApplyLocalPositionToVisuals (axleInfos [i]); } } private void Acceleration (AxleInfo axleInfo, float motor) { if (motor != 0f) { axleInfo.leftWheelCollider.brakeTorque = 0; axleInfo.rightWheelCollider.brakeTorque = 0; axleInfo.leftWheelCollider.motorTorque = motor; axleInfo.rightWheelCollider.motorTorque = motor; } else { Deceleration (axleInfo); } } private void Deceleration (AxleInfo axleInfo) { axleInfo.leftWheelCollider.brakeTorque = decelerationForce; axleInfo.rightWheelCollider.brakeTorque = decelerationForce; } private void Steering (AxleInfo axleInfo, float steering) { axleInfo.leftWheelCollider.steerAngle = steering; axleInfo.rightWheelCollider.steerAngle = steering; } private void Brake (AxleInfo axleInfo) { axleInfo.leftWheelCollider.brakeTorque = brakeTorque; axleInfo.rightWheelCollider.brakeTorque = brakeTorque; } } I know, this script was a little bit difficult but I am here to help you. Variable Name Variable Type Description axleInfos List List of AxleInfo Which contains a pair of wheels data. maxMotorTorque float maximum Torque is applicable on Vehicle. maxSteeringAngle float Maximum angle at which wheel is rotate. brakeTorque float Torque is applied when a brake is pressed. decelerationForce float This force is applied to stop the vehicle because of friction. ApplyLocalPositionToVisuals (AxleInfo axleInfo) This Method takes one argument: axleInfo. This method is used to Display rotation and position of WheelMeshes. FixedUpdate() This is Unity callBack used to do certain changes in physics at fixed time. Inside that, we will take Input. Vertical: W/Up Arrow for Forward & S/Down Arrow for Backward. Horizontal: A/Left Arrow for Left Side Rotation. & D/Right Arrow for Right Side Rotation. Space: To Stop(brake). Assign this Script to our “Car” GameObject. Add Size of AxleInfo to 2. Now add your Colliders and Meshes to appropriate Location. We have 3 methods to Control Car Acceleration(), Steering() and Brake(). You can relate all the methods listed below. These methods are works like how actually Vehicle we drive in reality Accelerator, Brake(No Clutch here). Acceleration() It is used to make the vehicle move forward and backward. If forward or backward buttons are not clicked then need to add Deceleration(). motorTorque is used to add torque (In forward or backward direction) in a vehicle. When the vehicle is moving at that time brakeTorque is needed to change to 0. Deceleration() It is used to stop the vehicle when forward and backward buttons are not pressed. Steering() It is used to turn angle of vehicle. steerAngle is used to change an angle of the the vehicle Brake() It is used to stop the vehicle using brakeTorque property. PART-3: ASSIGNING VALUES Finally at the end, This is the last thing to make your car drivable. Enable motor if you want to Apply Force and Suspension on That Wheel. Enable Steering if you want to give rotation Force on that Wheel. Maximum Motor Torque change as per your car’s Rigidbody mass. Maximum Steering Angle must be between (30-35). Brake Torque depends on how much Brake Torque you want to apply. Deceleration Force is must be less than Brake Torque. Tip Experiment with This Value to make your Car run smoothly. Caution Brake Torque and Deceleration Force value need to be much higher to stop usually(1e+5 to 1e+8).  

Vivek Tank

Vivek Tank

Sign in to follow this  
  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!