Unity Game Development: Projectile Launching and Animal Management Scripts

Codynn
5 Min Read

In this article, we will share two essential Unity scripts: one for launching projectiles and another for managing the behavior of an animal character in the game. These scripts are a part of our ongoing Unity tutorial series on YouTube, where we explain the concepts in detail. Here, we are sharing the code snippets for your convenience, along with a brief description of their functionalities.


ProjectileLauncher Script

The ProjectileLauncher script is designed to handle the logic for shooting projectiles in a Unity game. This script enables a GameObject to fire projectiles with a cooldown between shots, providing a smooth firing experience.

Code Snippet: ProjectileLauncher.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class ProjectileLauncher : MonoBehaviour
{
    [SerializeField]
    private Rigidbody projectileRigidBody;
    [SerializeField]
    private float projectilePower = 1500;
    [SerializeField]
    private GameObject muzzle;

    [SerializeField]
    private float COOLDOWN_TIME = 0.5f;
    private float coolDown = 0;

    // Start is called before the first frame update 
    void Start() {}

    // Update is called once per frame 
    void Update()
    {
        if (coolDown <= 0)
        {
            if (Input.GetButtonUp("Fire1"))
            {
                coolDown = COOLDOWN_TIME;

                // Instantiate the projectile. 
                Rigidbody aInstance = Instantiate(projectileRigidBody,
                        muzzle.transform.position, transform.rotation) as Rigidbody;

                // Add force. 
                Vector3 forward = transform.TransformDirection(Vector3.forward);
                aInstance.AddForce(forward * projectilePower);

                // Destroy the object after X seconds. 
                Destroy(aInstance.gameObject, 8);
            }
        }
        else
        {
            coolDown -= Time.deltaTime;
        }
    }
}

How It Works:

  • Instantiation and Force Application: When the “Fire1” button is released, a projectile is instantiated at the specified “muzzle” position and a forward force is applied to launch it.
  • Cooldown Management: To avoid continuous firing, the script includes a cooldown period (COOLDOWN_TIME) that prevents the next shot until the time elapses.
  • Object Cleanup: The instantiated projectile is destroyed after 8 seconds to prevent memory overload and maintain performance.

AnimalManager Script

The AnimalManager script controls an animal’s behavior in the game, such as walking towards the player, pausing at intervals, and resetting its position upon collision with a specific object. This script utilizes Unity’s Animator component to trigger animations based on the animal’s state.

Code Snippet: AnimalManager.cs

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class AnimalManager : MonoBehaviour
{
    [SerializeField]
    private string animalName = "Lion";
    private bool timeOn = false;
    private float countDown = 0;
    private Vector3 home = new Vector3();
    private GameObject player;
    private float currentSpeed = 3;
    private Animator anim;
    AnimatorStateInfo currentStateInfo;
    private int walkHash = Animator.StringToHash("Walk");

    // Start is called before the first frame update 
    void Start()
    {
        home = transform.position;
        home.y += 1;

        player = GameObject.FindWithTag("Player");
        anim = GetComponent<Animator>();

        timeOn = true;
        countDown = Random.Range(1.0f, 6.0f);
        currentSpeed = Random.Range(2.0f, 12.0f);
    }

    // Update is called once per frame 
    void Update()
    {
        if (timeOn)
        {
            countDown -= Time.deltaTime;
            if (countDown <= 0)
            {
                timeOn = false;
                transform.position = home;
            }
            else
            {
                return;
            }
        }

        AnimalWalk();
    }

    private void AnimalWalk()
    {
        Vector3 direction = player.transform.position - transform.position;
        direction.y = 0;
        float distance = direction.magnitude;

        if (direction.magnitude > 0)
        {
            Quaternion rotation = Quaternion.LookRotation(direction, Vector3.up);
            transform.rotation = rotation;
        }

        Vector3 normDirection = direction / distance;
        anim.SetInteger(walkHash, 1);

        currentStateInfo = anim.GetCurrentAnimatorStateInfo(0);
        if (currentStateInfo.IsName(animalName + "Walk"))
        {
            transform.position += normDirection * currentSpeed * Time.deltaTime;
        }
    }

    void OnCollisionEnter(Collision collision)
    {
        if (collision.gameObject.tag.Equals("Sphere"))
        {
            Destroy(collision.gameObject);
            transform.position = new Vector3(0, -1000, 0);

            timeOn = true;
            countDown = Random.Range(2.0f, 8.0f);
            currentSpeed = Random.Range(2.0f, 12.0f);
        }
    }
}

How It Works:

  • Walking Logic: The animal determines its direction towards the player and updates its rotation accordingly. It moves towards the player if the “Walk” animation state is active.
  • Collision Handling: When the animal collides with an object tagged “Sphere,” it hides itself and sets a new timer for when it will become visible again.
  • Randomized Behavior: Both the speed and the countdown time are randomized to make the animal’s behavior less predictable and more dynamic.

Conclusion

These scripts demonstrate fundamental concepts in Unity, such as instantiating objects, handling user input, managing animations, and creating interactive gameplay elements. Be sure to check out our YouTube channel for a more in-depth explanation and live coding session!

Feel free to use, modify, and expand these scripts for your own Unity projects. Happy coding! 🎮

Share This Article
Leave a comment

Leave a Reply

Your email address will not be published. Required fields are marked *