Click here to Skip to main content
15,885,278 members
Articles / All Topics
Technical Blog

Basic "shoot to target" in Unity 3D

Rate me:
Please Sign up or sign in to vote.
5.00/5 (3 votes)
22 Jul 2015CPOL 15.1K   3   2
Basic "shoot to target" in Unity 3D

First, let's create a new Unity 3d Project, and select 3D.

Let's add a terrain GameObject-3D-Terrain. Import Characters package Assets-Import Package-Characters, select all, and click Import. Find the ThirdPersonController in the Project pane (use the search tool if you can't find it) and add it to the scene.

Create a Cube GameObject-3d Object-Cube. Name it ShootBox. Create a Sphere GameObject-3d Object-Sphere, set its scale to 0.5 for x, y and z. Name it BulletPlaceHolder. Create a folder Resources. Drag the two recently created objects into the Resources folder. Create a Scripts folder. Create three scripts: Bullet.cs, Player.cs, and ShooterBox.cs and add their respective code.

Bullet.cs

C#
using UnityEngine;
using System.Collections;

public class Bullet : MonoBehaviour
{
    private float Speed = 3.5f;
    public GameObject Target = null;
    // Use this for initialization
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (Target != null)
        {
            float step = Random.Range(1,5) * Time.deltaTime;
            this.transform.position = Vector3.MoveTowards(this.transform.position, 
            	Target.transform.position + new Vector3(0,0.5f,0), step);
        }
    }

    public void OnTriggerEnter(Collider other)
    {
        Debug.Log(other.name);
        Player playerComponent = other.GetComponent<Player>();
        if (playerComponent != null)
        {
            int newHealth = playerComponent.Health - 1;
            if (newHealth == 0)
            {
                Time.timeScale = 0;
            }
            else
                playerComponent.Health = newHealth;
            GameObject.Destroy(this.gameObject);
        }
    }
}

Player.cs

C#
using UnityEngine;
using System.Collections;
using UnityEngine.UI;
 
public class Player : MonoBehaviour {
    public int Health = 100;
    public Text HealthText;
// Use this for initialization
void Start () {
}
 
// Update is called once per frame
void Update () { 
}
 
    void OnGUI()
    {
        HealthText.text = Health.ToString();
    }
}

ShooterBox.cs

C#
using UnityEngine;
using System.Collections;
 
public class ShooterBox : MonoBehaviour {
 
// Use this for initialization
    private GameObject player;
    private float lastTimeShooted = 0;
    public int ShootIntervalInSeconds = 15;
void Start () {
        this.player = GameObject.FindGameObjectWithTag("Player");
}
 
// Update is called once per frame
void Update () {
        if  ((lastTimeShooted + ShootIntervalInSeconds) < Time.time)
        {
            GameObject loadedResource = Resources.Load<GameObject>("BulletPlaceHolder");
            GameObject newInstance = GameObject.Instantiate<GameObject>(loadedResource);
            newInstance.transform.position = this.transform.position;
            Bullet bullet = newInstance.GetComponent<Bullet>();
            bullet.Target = this.player;
            lastTimeShooted = Time.time;
        }
}
}

Add the Bullet.cs script to the BulletPlaceHolder prefab. Add the ShooterBox.cs script to the ShooterBox prefab. Add the Player.cs script to the ThirdPersonController in the scene. Create a Canvas object and add two objects to it: HealthLabel and HealthText.

Go to the ThirdPersonController in the scene, in the inspector find the Health Text field below the Player script and assign the recently created HealthText object.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
CEO PTI Costa Rica
Costa Rica Costa Rica
Eduardo is an individual with knowledge is multiple academic fields,
where the two main are System Engineering and Psychology.
This not only allows Eduardo to work in the IT fields, but also give him the knowledge and abilities required to understand people behavior, and the factors involved that could affect a person, and even more than understand them, his Psychology studies give him the tools to help the individuals that require it.

Eduardo has also some knowledge in he videogame development field, and using tools such as
3ds max and Unity 3d.

Eduardo's main goal is actually to become a videogame profesional.

Profile:
* Bachellor in System Ingeneering
* 8+ years of experience

Linkedin profile: https://cr.linkedin.com/in/pticostarica

Comments and Discussions

 
QuestionShoot Pin
Member 903791113-Nov-17 19:45
Member 903791113-Nov-17 19:45 
QuestionFirst Person Pin
Member 903791113-Nov-17 18:37
Member 903791113-Nov-17 18:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.