Jump to content
  • Advertisement

Vivek Tank

Member
  • Content count

    5
  • Joined

  • Last visited

Community Reputation

3 Neutral

About Vivek Tank

  • Rank
    Newbie

Personal Information

  • Role
    Writer
  • Interests
    Audio
    Business
    Design
    Programming

Social

  • Twitter
    imVtank

Recent Profile Visitors

The recent visitors block is disabled and is not being shown to other users.

  1. Objective The main objective of this blog post is to give you an idea about ScriptableObject in Unity. What is Scriptable Object? What is the difference between ScriptableObject and Monobehaviour class? What are Pros and Cons of Scriptableobject? How to use ScriptableObject? Let’s undertstand all the questions by taking one ride of this blog about ScriptableObject According to Unity API documentation, "ScriptableObject is a class you can derive from if you want to create objects that don't need to be attached to game objects." Confuesed..? Don’t worry, if you didn’t get it. Here, I will Explain what it means. As we know, with Unity, everything is an Object. Monobehaviours are one of the Objects. GameObjects: In your scene, you can move around with transform. ScriptableObject is a kind of Object but, it can only Contain Data. So, they don’t get involved in the actual game. I hope you understood the definition of ScriptableObject. Let's discuss Pros and Cons of ScriptableObject. Prose of ScriptableObject: Built into Unity They’re very well maintained by Unity. You can interact with them very easily in Unity inspector. Can be saved as Assets You can create it as a mini file inside your project. You can update that and save that as per your game requirements. Can save during runtime If you change something during runtime it will actually remember that. Internal Solution When you are trying to get the data during run time of the game, you don’t worry about parsing external files which will come into play more. Large amounts of Data You can save millions of integers inside of a ScriptableObject. So, there’s a lot of space(no size limit function). Add to Structure as you go As you’re building a scriptable object and create few instances of it and realize ,ohh I need a new setting for ‘moveSpeed’ or whatever additional variable you need you can add, it won’t disrupt your variable. Deleting variable can have a little bit negative impact. Cons of ScriptableObject: Requires an editor scripting If you want to make assets out of scripting then you have to know a little bit about it. Can’t edit outside Unity If you’re working strictly with Unity that’s not really a huge issue. But if you have like team base solution, where you want to send files to someone and have them edit then it won’t work. Can’t save once deployed Can’t save during runtime,once you’ve built the game meaning that this is not solution for saving a player’s data.This is only for saving game development data. Let's take one example to understand how to use ScriptableObject in game. Let me give you one task first. Suppose, we have 10 level game and at each level the behaviour of enemy will change. Any Ideas, how you will do this?? Ahh, You might think that make 10 prefab of 10 different enemy and assign it to each level. Right?? Are you sure, it really a good practise? Actually, the answer is No. "Because one enemy object may have 4 variable and Update() function with it, and suppose is uses 4 Mb of memory, so 10 level enemy may require 40 Mb of memory amount." So, here is the solution. Use ScriptableObject to store data of enemy Object. Let’s, develop our mini game with ScriptableObject. First, I will create a simple script without using a ScriptableObject. (As per our first thought about creating different prefab of each different enemy and assign it to each level ) Step 1 Create an empty GameObject name it Enemy. Step 2 Create C# script and name it EnemyMove Write following code in EnemyMove.cs public class EnemyMove : MonoBehaviour { #region PUBLIC_VARIABLES public string name; public int moveSpeed; public Color color; public string colorName; public SpriteRenderer spriterendere; #endregion #region PRIVATE_VARIABLES private float speed; Vector3 newPosition; #endregion #region UNITY_CALLBACKS void Update () { ChangeSpeed(); gameObject.name = name; spriterendere.color = color; newPosition=transform.position; newPosition.y = Mathf.Sin (Time.time) * speed; transform.position = newPosition; } #endregion #region PROVATE_METHODS private void ChangeSpeed(){ speed = Mathf.MoveTowards (speed,moveSpeed,Time.deltaTime); } #endregion } Step 3 Assign it to empty GameObject(Enemy). EnemyMove script has three public variables. If game has so many enemy GameObject with enemyMove script with it then uses lots of memory. For that as per our solution ScriptableObject, we can make a EnemyData script Instead of storing these variable within EnemyMove script. Step 4 Create C# script name it EnemyData. which inherits ScriptableObject instead of Monobehaviour. Write the following code in EnemyData.cs. public class EnemyData : ScriptableObject { #region PUBLIC_VERIABLE public string name; public int moveSpeed; public Color color; public string colorName; #endregion } Step 5 Change the code inside ‘EnemyMove’,which was previously created. Create One public variable ‘data’ which is the reference of ‘EnemyData’. Remove the public which is already in ‘EnemyData’ Change according to following code. public class EnemyMove : MonoBehaviour { #region PUBLIC_VARIABLES public EnemyData data; public SpriteRenderer spriterendere; #endregion #region PRIVATE_VARIABLES private float speed; Vector3 newPosition; #endregion #region UNITY_CALLBACKS void Update () { ChangeSpeed(); gameObject.name = name; spriterendere.color = data.color; newPosition=transform.position; newPosition.y = Mathf.Sin (Time.time) * speed; transform.position = newPosition; } #endregion #region PROVATE_METHODS private void ChangeSpeed(){ speed=Mathf.MoveTowards (speed,data.moveSpeed,Time.deltaTime); } #endregion } Now you can see that inside the Inspector for Enemy GameObject on ‘Data’ variable will appear, Any idea..what you suppose assign over here?? Follow me... Step 1 Add one line in EnemyData.cs as follow [CreateAssetMenu(fileName="EnemyData" ,menuName="Enemy Data")] public class EnemyData : ScriptableObject { #region PUBLIC_VERIABLE public string name; public int moveSpeed; public Color color; public string colorName; #endregion } Step 2 Create one folder Game data and do following Step 3 Name it as you like. Now, you can see all the variable inside the EnemyData in inspector window, you can change values of variable here. Step 4 Assign this into ‘EnemyMove’ script I am sure you got all the answers now. Conclusion ScriptableObject are really good for the fact that they can break your data into more sizeable chunks. So that you’re not eating up a lot of memory. ScriptableObject is only for development purpose.
  2. Objective The main objective of this blog post is to give you an idea about how to do Sprite Sheet Animation in Unity3D. Are you looking for animation in your 2D games? Do you want your Character have some real feel and look more living ? Then here it is, I’ve brought you some easy and quick ways to make your game look attractive and give a real life feel to the character of your game. In this post we will learn how to give animation to your game character with 2 easy ways. By Animation And Animator controller. By Scripting. Interesting right..? So tight up your seat belts and get ready for this joyful ride! Let’s start with the first option. 1. By Animation And Animator Controller First set up the scene like the given image. Don't forget to add sprites folder that will be use for the the different animation to your scene, if you don't have the Sprites you can download it from here. Create a 2D sprite object and assign the first sprite of the idle Animation to it. (Idle animation is the animation in which the character is just standing still and breathing no other activity). Create the Script named AnimationWithScripting and attach it to hero Object. Now, follow the below steps to create the different animation. First select all the sprites of Idle Animation folder and drag it on our hero object and drop there, a new animation will be created. Then Unity will ask to name the animation name it as Idle. Then select all the sprites of Kick Animation folder and drag it on our hero objectand drop there , a new animation will be created. Again Unity will ask to name the animation name it as Kick. Then select all the sprites of Walking Animation folder and drag it on our hero objectand drop there, a new animation will be created. Again Unity will ask to name the animation name it as Walk. I hope you all are ready with your 3 animations. The animator controller will be automatically added to our hero object. Now set the transitions and trigger as per the below image. See what Triggers are to be set in the following transitions: Transition Trigger Idle -> Walking transition Walk Walking -> Idle transition Idle Kick -> Walking transition Walk Walking -> Kick transition Kick Idle -> Kick transition Kick Kick -> Idle transition Idle Let’s see the code is to be written in the Script ScriptToAnimate.cs using UnityEngine; using System.Collections; public class ScriptToAnimate : MonoBehaviour { public Animator animator; void Update() { if (Input.GetKeyDown(KeyCode.I)) { animator.SetTrigger("Idle"); } if (Input.GetKeyDown(KeyCode.K)) { animator.SetTrigger("Kick"); } if (Input.GetKeyDown(KeyCode.W)) { animator.SetTrigger("Walk"); } } } Let’s see what's there in the scripts. Name Type Description Animator animator; variable To store the reference of the Animator Controller of the object Update() Unity Callback To write conditions according which the animation is To be triggered Go to Unity now and play the scene you will see the idle animation playing default. Now press the keys I, K and W respectively and check. Did you see your character..? Yeyy ! your character got life. Your character is breathing, kicking and walking. I'm sure you are on the right track. Now, let’s move to another method. By Scripting First set up the scene like the given image. Don't forget to add sprites folder that will be use for the the different animation to your scene, if you don't have the Sprites you can download it from here. Create a 2D sprite object and assign the first sprite of the idle Animation Create the Script named as AnimationWithScripting and attach it to hero Object and write the following code in it AnimationWithScripting.cs using UnityEngine; using System.Collections; public class AnimationWithScripting : MonoBehaviour { public SpriteRenderer spriteRenderer; public Sprite[] walk; public Sprite[] idle; public Sprite[] kick; void Start() { StartCoroutine(Idle()); } void Update() { if (Input.GetKeyDown(KeyCode.I)) { StopAllCoroutines(); StartCoroutine(Idle()); } if (Input.GetKeyDown(KeyCode.K)) { StopAllCoroutines(); StartCoroutine(Kick()); } if (Input.GetKeyDown(KeyCode.W)) { StopAllCoroutines(); StartCoroutine(Walk()); } } IEnumerator Idle() { int i; i = 0; while (i < idle.Length) { spriteRenderer.sprite = idle[i]; i++; yield return new WaitForSeconds(0.07f); yield return 0; } StartCoroutine(Idle()); } IEnumerator Walk() { int i; i = 0; while (i < walk.Length) { spriteRenderer.sprite = walk[i]; i++; yield return new WaitForSeconds(0.07f); yield return 0; } StartCoroutine(Walk()); } IEnumerator Kick() { int i; i = 0; while (i < kick.Length) { spriteRenderer.sprite = kick[i]; i++; yield return new WaitForSeconds(0.07f); yield return 0; } StartCoroutine(Kick()); } } Now go to Unity and add the sprites of walking, kicking and idle state in their following lists in the inspector as per the image. Let’s see what's there in the script. But wait... In this script, the coroutine is used for Sprite Sheet animation. If you don’t know how to use coroutine. Don't worry our coroutine unity blog post will help you. Trust me you will be master in 10mins. Name Type Description Start() Unity Callback To start the idle coroutine. SpriteRenderer spriteRenderer; variable To store the reference of the spriterenderer of the object. Sprite[] walk; list To Store walking Sprites Sprite[] idle; list To store idle Sprites Sprite[] kick; variable To store Kicking Sprites Update() Unity Callback To write conditions according which the animation is played IEnumerator Idle() coroutine To Run the Idle Animation IEnumerator Kick() coroutine To Run the Kicking Animation IEnumerator Walk() coroutine To Run the Walking Animation Now, go to Unity and play the scene you will see the Idle animation playing default. Now press the keys I,K and W respectively and check. Yeahhhhh ! Again you see character, its breathing kicking and walking. But wait which one is more optimised? Yes, maybe you would be having the same question. Both the methods run the same way when checked in the profiler. So, it's up to you whichever you feel easy and quick and in accordance to the requirement of your game. Feel free to contact us if you really liked this blog. And don’t forget to share your comments below!
  3. Objective The main objective of this blog post is to give you an idea about Camera Shake in Unity3D. Are You looking for giving some real feel to your game ? Do you want to add some screen shaking effect to your game ? Then you are at the right place ! A great way to add some real feel to your game is camera shaking. It’s great for signifying the action and making your camera feel more real and part of game. So, if you want to add camera shake in your game then you are at the right place. In this blog, I will show you how to create your own camera shake effect in 3 ways. Let’s try it with scripting first. 1. By scripting First setup a scene like this in Unity. Create an empty game object named Explodestar and a particle system in child to get more effective look. Create a script named Explodestar attached it to ExplodeStar gameobject to play particle system on playing game. Create another script named CameraShake and attach it to camera you want to give the shaking effect. The code in the scripts is shown as below. CameraShake.cs using UnityEngine; using System.Collections; public class CameraShake : MonoBehaviour { public IEnumerator Shake(float duration, float magnitude) { Vector3 orignalPosition = transform.position; float elapsed = 0f; while (elapsed < duration) { float x = Random.Range(-1f, 1f) * magnitude; float y = Random.Range(-1f, 1f) * magnitude; transform.position = new Vector3(x, y, -10f); elapsed += Time.deltaTime; yield return 0; } transform.position = orignalPosition; } } In this script, I have used the coroutine concept for shaking the camera. If you don’t know how to use coroutine in Unity you can check this blog. Trust me you will be master in 10 Minutes. Name Method/variable/coroutine Description Shake() coroutine Coroutine used for shaking camera Vector3 orignalPosition variable To store the original position of camera float elapsed variable To Store Elapsed time float x variable To store random x value float y variable To store random y value ExplodeStar.cs using UnityEngine; using System.Collections; public class ExplodeStar : MonoBehaviour { public ParticleSystem explodePartical; public CameraShake cameraShake; void Update() { if (Input.GetKeyDown(KeyCode.E)) { explodePartical.Play(); StartCoroutine(cameraShake.Shake(0.15f, 0.4f)); } } } Name Method/variable/coroutine Description Update() Unity Callback To check whether User Presses Key E ParticleSystem explodePartical; variable To store reference of particle System CameraShake cameraShake; variable To store reference of Camera explodePartical.Play(); method To Play the particle system StartCoroutine(cameraShake.Shake(0.15f, 0.4f)); method To start coroutine for Camera Shaking Now go back to Unity and hit play button and press key (E). Woooohooooo! You can see the screen shaking . This was simple and quick way to shake the camera. But wait, It has some limitation. It doesn’t rotate the camera in any way and there is no way to control the roughness. It just moves the camera every frame and using coroutine is bit clunky sometimes. So, if you want smoother camera shake this is not the way to go. Let’s try it with another way using the animation and check if it fulfills our demands. 2. By Using Animation First setup a scene like this in Unity. Add animator to main camera and create 2 animations idle and shake in that animator. In ideal animation start recording and set the camera to its original position. And in shake animation move position of camera on every two frame as you want to shake it. Now go to animator and create a trigger shake. Make transition from idle to shake and uncheck the ‘has exit time’ checkbox and set transition time to 1. Now make transition from shake to idle and set transition time to 1 but don’t uncheck has exit time. Now make empty object named ShakeWithAnimation and add ShakeWithAnimation Script to it and has a particle system in child to see it more effective. ShakeWithAnimation.cs using UnityEngine; using System.Collections; public class ShakeWithAnim : MonoBehaviour { public Animator camAnim; public ParticleSystem explodeStar; void Update() { if (Input.GetKeyDown(KeyCode.A)) { camAnim.SetTrigger("Shake"); explodeStar.Play(); } } } Name Method/variable/coroutine Description Update() Unity Callback Used for checking whether User Presses Key A ParticleSystem explodeStar; variable To store reference of particle System Animator camAnim; variable To store reference of Camera Animator explodePartical.Play(); method To Play the particle system camAnim.SetTrigger("Shake"); method To set Trigger for Camera Animation for Shaking. Go to the Unity and play the scene and press A. Oh Yeah! The screen shook again so you learned one more way to shake the camera. But wait, all condition are fulfilled but, what about roughness? Was there any way to control it using animation? Nahhhh! Then how can we do that? Yes, I know the same question is there in your mind. Let’s try the last way and check it out. 3. By using plugin First make new scene in Unity. Now go to asset store and download the plugin EZ Camera Shake (this is recommended by me as I use this and is very good but you can use any other plug in of your choice). After finishing downloading EZ CAMERA SHAKE, import it to your scene. The folder EZCameraShake will be added in your scene. Add script CameraShaker of EZCameraShake to main camera and set the variables as you want. Now create empty object and name it ExplodeHeart. Then give particle system in child for more effective look. Now create and add ExplodeHeart script to it. Add EZCameraShake namespace to your script. ExplodeHeart.cs using UnityEngine; using System.Collections; using EZCameraShake; public class ExplodeHeart : MonoBehaviour { public ParticleSystem explodePartical; void Update() { if (Input.GetKeyDown(KeyCode.H)) { explodePartical.Play(); CameraShaker.Instance.ShakeOnce(4f, 4f, 0.15f, 1f); } } } Name Method/variable/coroutine Description Update() Unity Callback Used for checking whether User Presses Key H ParticleSystem explodePartical; variable To store reference of particle System explodePartical.Play(); method To Play the particle system CameraShaker.Instance.ShakeOnce(4f, 4f, 0.15f, 1f); method To call ShakeOnce Method of CameShaker Script Of EZCAmeShake passing magnitude, roughness, fadInTIme and fadeOutTime. Now go to Unity and play the scene and press H. Yeah! The screen shaking was so smoother than the both the other way, wasn’t it? By this way you created your camera shake with the plugin. But wait, does this mean that the shaking camera with the script and animation was bad idea. Nope, instead the last way would give more load on your memory while running so if you don’t need this smoother shaking and roughness controlled camera shake the scripting one is really quick and easy. So you have to be wise while choosing any one of the methods of camera shaking in your game according to your requirement.
  4. 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).
  5. This article provides a brief introduction to creating Homing Missiles in a 2D game. A Homing Missile is a missile that locks onto and chases a target until it reaches the target and explodes. We'll be using the Unity engine, and a script for the Homing missile is also included and explained in the article. Scene Setup Create two 2D Objects named “Missile ” and “Target” Add a sprite to these 2D Objects (You can download the project from below link) Add rigidBody 2D in missile and add Script also name it as ”Homing Missile” Implementation To implement a basic homing missile we could use MoveToward/Lerp until the missile reaches its target. Using MoveToward/Lerp, the missiong will reach the target properly, but its movement will be very linear - there is no feel of a homing missile. To implement a better feel, we need to simulate with better physics. Let's walk through a solution: 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; } } 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 The Math Here is a visualization of the path our homing missile needs to take on a moving target. Let's talk about how to implement this. First, you need “Direction”. Step 1 We subtract the two vectors, targetPosition and missilePosition to get the direction. direction= targetPosition (target.position) - missilePosition(rb.position); Step 2 We convert the direction vector to a unit vector through normalization. direction.Normalize(); Step 3 Calculate the rotation vector. The rotation vector will be the cross product of our direction vector and our missile's up vector. The rotation vector will be the z-axis of the cross product. In the diagram below the blue arrow is our direction, the red arrow is the up vector of our missile's transform, and the green arrow is our resulting z-axis component of the cross product between direction and up. float rotateAmount=Vector3.Cross(direction,transform.up).z; Step 4 Next, we change the angularVelocity of the missile's rigidBody to control the orientation of our missile. We use an angleChangingSpeed factor to control the speed of rotation. rb.angularVelocity = -angleChangingSpeed * rotationAmount Step 5 And finally we add velocity to our rigidBody, which controls the translation of our missile in the environment. rb.velocity = tranform.up * movementSpeed But wait... We aren't done yet. In the code above we have two movement factors that need to be balanced: angleChangingSpeed and movementSpeed. In the above Image, the missile is moving toward the target, there is no problem here. However, in this image we have one tick of the simulation and the target has moved to a new position. The missile is oriented toward the target due to angular velocity (red), but it continues to move toward the target's previous position due to its velocity (black). As we can see, the missile's velocity moves it behind the target (black) while the angular velocity (red) tries to pull the missile to the target. This can result in the missile falling into a stable orbit around the target and never reaching its goal. We can balance this with the angleChangingSpeed and movementSpeed parameters. There is no particular formula to balance these parameters. The necessary parameters will depend on your gameplay and game design. Be careful with extremes for movementSpeed, positive or negative. Too slow and your missiles won't feel like homing missiles, and too fast will lead to them being trapped in orbit. Same with angleChangingSpeed. Too small it will be in orbit, and too high you will lose the feel of homing missiles. I hope this article has been useful and hope to see homing missiles in your game! [Wayback machine archived copy]
  • 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!