Sunday, October 21, 2018

Physics based aircraft 2 / 2 - Gun

Lets arm our aircraft from previous tutorial with a simple gun. We will need two scripts (one for a gun and one for a projectile), and also a prefab for projectile itself. For projectile, we'll use Particle System. It's very useful and powerful component, you can read about it here if you are curious. But for now, just create one and set it up according to these screenshots: Next, we should create a script for our projectile, lets call it Projectile.cs
using UnityEngine;
 
public class Projectile : MonoBehaviour
{
    // Reference to our Rigidbody to use later
    private Rigidbody rb;
 
    // Reference to our ParticleSystem to use later
    private ParticleSystem ps;
 
    // Use this for initialization
    void Start()
    {
        // Find our Rigidbody
        rb = GetComponent<Rigidbody>();
 
        // Find our ParticleSystem
        ps = GetComponent<ParticleSystem>();
 
        // Make sure our projectile disappears eventually
        // even if dont hit anything
        Invoke("Die", 5);
    }
 
    // Destroy nicely our projectile
    void Die()
    {
        // Stop emiting particles
        ps.Stop();
 
        // Disable collisions
        rb.detectCollisions = false;
 
        // Actually destroy after 2 seconds (to let particle emitter finish)
        Destroy(gameObject, 2);
    }
 
    // What should happen if we collide with something
    private void OnCollisionEnter(Collision collision)
    {
        // Disable inheriting velocity
        var iv = ps.inheritVelocity;
        iv.enabled = false;
 
        // Emit some particles to simulate impact
        for (int i = 0; i < 20; i++)
        {
            ps.Emit(new ParticleSystem.EmitParams()
            { velocity = collision.contacts[0].normal + Random.onUnitSphere * 2 }, 1);
        }
 
        // Destroy our projectile
        Die();
    }
}
Now we can add Rigidbody, Sphere Collider and our new Projectile script. Set them up according to next screenshot, and create prefab out of our Projectile by dragging it from the Hierarchy window on the left to the Assets window on the bottom (you can delete projectile from the scene afterwards). It's time to make a gun. Create new script, Gun.cs:
using UnityEngine;
 
public class Gun : MonoBehaviour
{
    //Our projectile prefab
    public Rigidbody projectilePrefab;
 
    //How fast projectiles will go
    public float initialVelocity = 100.0f;
 
    // How often our gun can fire
    public float fireDelay = 0.25f;
 
    // How much time since last shoot
    private float t = 0;
 
    // Reference to our Rigidbody to use later
    private Rigidbody rb;
 
    // Use this for initialization
    void Start()
    {
        // Find our Rigidbody
        rb = GetComponentInParent<Rigidbody>();
    }
 
    // Update is called once per frame
    void Update()
    {
        // Increase our shoot timer
        t += Time.deltaTime;
 
        // If it isn't too early and we are pressing Fire1 button (left CTRL by default)
        if (t > fireDelay && Input.GetButton("Fire1"))
        {
            // Reset shoot timer
            t = 0;
 
            // Instantiate our projectile and send it flying
            var pr = Instantiate(projectilePrefab, transform.position, transform.rotation);
            pr.velocity = transform.forward * initialVelocity;
 
            // If we have a rigidbody, projectile should inherit it's velocity
            if (rb != null)
            {
                pr.velocity += rb.velocity;
            }
        }
    }
}
Lets install our new gun into our ship. Create empty GameObject as a child of our ship, rename it to Gun and position it in front of the ship. Make sure it's quite far from the ship's own collider, or else you might fly right into the projectile you just launched and kill yourself... It will launch projectiles in the direction of blue arrow, so make sure it's rotated correctly too.

When you are done, add Gun.cs script to our new GameObject and drag Projectile prefab into 'Projectile Prefab' field of our gun: Congratulations, now your ship is armed! Feel free to experiment with adding multiple guns, changing rate of fire or improving visuals of projectiles.

Saturday, October 20, 2018

Physics based aircraft 1 / 2 - Basic Movement

Let's make simple, player controllable aircraft.

I used ship model from here:
https://www.assetstore.unity3d.com/en/?stay#!/content/29459
And buildings models from here:
https://www.assetstore.unity3d.com/en/?stay#!/content/66885

First, let's prepare our ship object. Put your ship model in the scene (make sure it's positioned in front of the camera), add Rigidbody and Mesh Collider components to it. Make sure to set parameters marked in red accordingly.

Our ship wont do much just yet, we need a way to control it. Aircrafts have three principal axes that can be controlled, pitch, yaw and roll: Lets start with controls for pitch and roll first. Create new script, 'PlayerShip.cs', and add it to our ship. Here is how it should look like:
using UnityEngine;
 
public class PlayerShip : MonoBehaviour
{
    // Max torque for roll
    public float rollTorque = 100;
 
    // Max torque for pitch
    public float pitchTorque = 50;
 
    // Reference to our Rigidbody to use later
    private Rigidbody rb;
 
    // Use this for initialization
    void Start()
    {
        // Find our Rigidbody
        rb = GetComponent<Rigidbody>();
 
        // AddRelatioveTorque sometimes acts weird if this isn't reset...
        rb.inertiaTensorRotation = Quaternion.identity;
    }
 
    // FixedUpdate is called every Time.fixedDeltaTime
    void FixedUpdate()
    {
        // Get value of horizontal axis (left/right arrow or a/d keys),
        // returns value in range [-1.0f, 1.0f]
        var h = Input.GetAxis("Horizontal");
 
        // Get value of vertical axis (up/down arrow or w/s keys)
        var v = Input.GetAxis("Vertical");
 
        // Add torque along each axes
        rb.AddRelativeTorque(v * pitchTorque, 0, -h * rollTorque
            , ForceMode.Force);
    }
}
With this script assigned to our ship, you should be able to rotate it along x and z axes. It's still not very exciting though... Let's make our ship move. Declare parameter thrust of type float, give it default value of 50, and add this line to our FixedUpdate method:
// Add some forward thrust
rb.AddRelativeForce(Vector3.forward * thrust, ForceMode.Force);
Your PlayerShip script should look like this:
using UnityEngine;
 
public class PlayerShip : MonoBehaviour
{
    // Max torque for roll
    public float rollTorque = 100;
 
    // Max torque for pitch
    public float pitchTorque = 50;
 
    // Thrust
    public float thrust = 50;
 
    // Reference to our Rigidbody to use later
    private Rigidbody rb;
 
    // Use this for initialization
    void Start()
    {
        // Find our Rigidbody
        rb = GetComponent<Rigidbody>();
 
        // AddRelatioveTorque sometimes acts weird if this isn't reset...
        rb.inertiaTensorRotation = Quaternion.identity;
    }
 
    // FixedUpdate is called every Time.fixedDeltaTime
    void FixedUpdate()
    {
        // Get value of horizontal axis (left/right arrow or a/d keys),
        // returns value in range [-1.0f, 1.0f]
        var h = Input.GetAxis("Horizontal");
 
        // Get value of vertical axis (up/down arrow or w/s keys)
        var v = Input.GetAxis("Vertical");
 
        // Add torque along each axes
        rb.AddRelativeTorque(v * pitchTorque, 0, -h * rollTorque
            , ForceMode.Force);
 
        // Add some forward thrust
        rb.AddRelativeForce(Vector3.forward * thrust, ForceMode.Force);
    }
}
It's probably good idea to make camera child to our ship object, so it will follow it. I also changed camera's Field of View to 90, so its easier to see where we are going.
If all went good, you should be able to fly around. However, controlling our aircraft is a bit awkward, since we don't have any control over 'yaw' axis. Normally you control it with rudder, but since we don't want to over-complicate our controls, we are going to cheat a bit. We will add some amount of yaw automatically depending on our roll angle. Add parameter yawTorque with default value of 50, and add these lines to FixedUpdate method:
// Calculate cosine of our 'roll' angle
var dot = Vector3.Dot(-transform.right, Vector3.up);
 
// Add some yaw depending on roll angle
rb.AddTorque(0, dot * yawTorque, 0, ForceMode.Force);
As a finishing touch, let's restart our game if we crash into something. Add following method to PlayerShip class:
// What should happen if we collide with something
private void OnCollisionEnter(Collision collision)
{
    // Lets just reload our scene
    SceneManager.LoadScene(SceneManager.GetActiveScene().name);
}
If your ship doesn't want to collide with anything, make sure all of your scenery objects have some kind of colliders assigned.
Final PlayerShip.cs should look like this:
using UnityEngine;
using UnityEngine.SceneManagement;
 
public class PlayerShip : MonoBehaviour
{
    // Max torque for roll
    public float rollTorque = 100;
 
    // Max torque for yaw
    public float yawTorque = 20;
 
    // Max torque for pitch
    public float pitchTorque = 50;
 
    // Thrust
    public float thrust = 50;
 
    // Reference to our Rigidbody to use later
    private Rigidbody rb;
 
    // Use this for initialization
    void Start()
    {
        // Find our Rigidbody
        rb = GetComponent<Rigidbody>();
 
        // AddRelatioveTorque sometimes acts weird if this isn't reset...
        rb.inertiaTensorRotation = Quaternion.identity;
    }
 
    // FixedUpdate is called every Time.fixedDeltaTime
    void FixedUpdate()
    {
        // Get value of horizontal axis (left/right arrow or a/d keys),
        // returns value in range [-1.0f, 1.0f]
        var h = Input.GetAxis("Horizontal");
 
        // Get value of vertical axis (up/down arrow or w/s keys)
        var v = Input.GetAxis("Vertical");
 
        // Add torque along each axes
        rb.AddRelativeTorque(v * pitchTorque, 0, -h * rollTorque
            , ForceMode.Force);
 
        // Calculate cosine of our 'roll' angle
        var dot = Vector3.Dot(-transform.right, Vector3.up);
 
        // Add some yaw depending on roll angle
        rb.AddTorque(0, dot * yawTorque, 0, ForceMode.Force);
 
        // Add some forward thrust
        rb.AddRelativeForce(Vector3.forward * thrust, ForceMode.Force);
    }
 
    // What should happen if we collide with something
    private void OnCollisionEnter(Collision collision)
    {
        // Lets just reload our scene
        SceneManager.LoadScene(SceneManager.GetActiveScene().name);
    }
}
And our ship's parameters should look like this: Congratulations, you made your ship fly! If you'd like to see how final thing looks like, click here and wait for it to load :3

As an optional step, if you'd like your ship to self stabilize by trying to go back to horizontal orientation, you can add this script to it.
using UnityEngine;
 
public class Stabilize : MonoBehaviour
{
    // How much to push object into desired orientation. 
    // If your object oscilates too much, add some Angular Drag in the rigidbody.
    public float torque = 100;
 
    // Reference to our Rigidbody to use later
    private Rigidbody rb;
 
    // Use this for initialization
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }
    
    // FixedUpdate is called every Time.fixedDeltaTime
    void FixedUpdate()
    {
        Vector3 targetDirection = Vector3.up;
 
        // get its cross product, which is the axis of rotation to
        // get from one vector to the other
        Vector3 cross = Vector3.Cross(transform.up, targetDirection);
 
        // apply torque along that axis according to the magnitude of the cross product 
        // and maximum torque.
        rb.AddTorque(cross * torque);
    }
}

Monday, October 15, 2018

3D Animations 2 / 2

This time we'll make our tiger walk around. To do that, we are going to make TigerAnimator blend 'idle' and 'walk' animations based on new 'Speed' parameter.

Lets add 'Speed' parameter to our TigerAnimator first.

Then, we should rename our 'idle' state to 'locomotion', and make a blend tree in it.

Double click on 'locomotion' state, it will open our newly created blend tree in animator window. Add 'idle' and 'walk' animations too it. Make sure that Parameter is set to 'Speed'.

We need to change our Tiger.cs script to use 'Speed' parameter. Open it and modify Update method like this.

Now our tiger should walk forward when we press up arrow or 'w' key

What happens when we go backwards though? Our tiger just slides back, that's no good... We don't have 'walk backwards' animation, however, we can just use normal walk animation and play it in reverse. Go back to our blend tree, add 'walk' animation again and set thresholds and speed like here.

Now our tiger can walk backwards! Another small issue is that when we press Fire1 while holding up or down keys, our tiger slides around while roar animation plays. Lets make our tiger stop before roaring. To do that, we have to update our Tiger.cs script again. As a finishing touch, we will also add turning.

Congratulations! You now have animated game character who can walk around and roar at things!

3D Animations 1 / 2

To use animations in unity, you can either make them yourself in the editor, or use a model that already has them. In this example, I used free model with animations from the asset store that you can download here. Alternatively, you can download it straight from the Asset Store, but some assets will have different names.

After placing model in our scene, we should create 'Animator Controller' for it and call it TigerAnimator.
Create 'Animator Controller'

Assign our TigerAnimator to our Tiger model.
Assign TigerAnimator

Now double click on TigerAnimator to open Animator window (you can do that in either Inspector or Project panels).
Animator panel

Find 'idle' animation and drag it into Animator window to create new state.
Creating 'idle' state

If you 'Play' your project now, you should have your model playing animation you picked.
Playing idle animation

Lets add another one. Find 'roar' animation and drag it to the Animator window.
Creating 'roar' state

We need a way to tell our TigerAnimator to play 'roar' animation. To do that, we need to add parameter of type 'trigger', and then use it in transition from idle state to roar state.
Roar trigger

To create new transition, right click on 'idle' state, pick 'Make Transition', and connect it to 'roar' state.
Creating transition from 'idle' to 'roar' state

Select our new transition and add 'Roar' trigger as new condition to it. That way it will play whenever we fire 'Roar' trigger from script. Also disable 'Has Exit Time' option, since we don't want 'roar' state to wait till idle animation is finished.
Setting up transition


Now we can add script to control out Tiger. With our Tiger model in the scene selected, click on The Add Component button and select 'New script'. Lets name it Tiger.
Adding Tiger.cs script
Open our newly created Tiger.cs script by double clicking on it (Visual Studio might take few seconds to start), and make it look like this.


Now when you 'Play' your project, tiger should play 'roar' animation when you press Fire1 button

There is a problem though, our tiger never stops roaring... We forgot to add transition from 'roar' state back to 'idle' state... Lets fix this! Open animation window, select 'roar' state and make new transition to 'idle' state.
Creating transition back from 'roar' to 'idle' state
Now our tiger should roar only once whenever we press Fire1 button.

As an exercise, you can add 'Attack' animation in the same way, just connect it to Fire2 button instead (left ALT key by default).

In part two, we will make our tiger walk around Part 2