图形学课设 塔防游戏

Tower Defence Demo

四人小组作业,通过unity实现
塔攻击的代码

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

public class AttackTower : MonoBehaviour
{
    Transform firePosition;
    public GameObject bulletPrefab;
    // Start is called before the first frame update
    void Start()
    {
        firePosition = transform.Find("FirePosition");
    }

    // Update is called once per frame
    void Update()
    {
        
    }
 
    public void Fire(Transform _target)
    {
        GameObject bullet = GameObject.Instantiate(bulletPrefab, firePosition.position, firePosition.rotation);
        bullet.GetComponent<Missile>().SetTarget(_target.gameObject.transform);
        Destroy(this);
    }
}

子弹攻击代码

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

public class Bullet : MonoBehaviour
{
    public int damage = 50;
    public float speed = 20;
    public GameObject explosionEffectPrefab;
    private Transform target;



    // Update is called once per frame
    void Update()
    {
        if (target == null)
        {
            Destroy(this.gameObject);
            return;
        }
        transform.LookAt(target);
        transform.eulerAngles += new Vector3(0, -90, 90);
        transform.position = Vector3.MoveTowards(transform.position, target.position, Time.deltaTime * speed);

    }

    public void SetTarget(Transform _target)
    {
        this.target = _target;
    }

    private void OnTriggerEnter(Collider other)
    {
        if(other.tag == "Enemy")
        {
            if (other.GetComponent<Enemy1>() != null)
            {
                other.GetComponent<Enemy1>().TakeDamage(damage);
            }
            else
            {
                other.GetComponent<Enemy2>().TakeDamage(damage);
            }
            GameObject.Instantiate(explosionEffectPrefab, transform.position, transform.rotation);
            Destroy(this.gameObject);
        }
        if(other.tag == "Shield")
        {
            Debug.Log("击中护盾");
            Destroy(this.gameObject);
        }
    }
}

生成敌人波次

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

public class EnemySpawner : MonoBehaviour
{
    public static int enemyAliveCount = 0;
    public Wave[] waves;
    public Transform START;
    public Transform enemyGroup;

    public Transform START2;
    public Transform enemyGroup2;

    private Coroutine coroutine;
  //  public static int enemyAliveCount2 = 0;
    public Wave[] waves2;
    // Start is called before the first frame update
    void Start()
    {
        coroutine = StartCoroutine(SpawnerEnemy());
    }
    public void stop()
    {
        StopCoroutine(coroutine);
    }

    IEnumerator SpawnerEnemy()
    {
        foreach (Wave wave in waves)
        {
            for(int i = 0; i < wave.count; i++)
            {
                GameObject.Instantiate(wave.enemyPrefab, START.position, Quaternion.identity,enemyGroup);
                enemyAliveCount++;
                yield return new WaitForSeconds(wave.rate);//等待每个敌人出现间隔的时差
            }
            //while(enemyAliveCount != 0)
            //{
            //    yield return 0;
            //}
            yield return new WaitForSeconds(wave.waveRate);//等待每波之间的时差
        }


        foreach (Wave wave in waves2)
        {
            for (int i = 0; i < wave.count; i++)
            {
                GameObject.Instantiate(wave.enemyPrefab, START2.position, Quaternion.identity, enemyGroup2);
                enemyAliveCount++;
                yield return new WaitForSeconds(wave.rate);//等待每个敌人出现间隔的时差
            }
            //while(enemyAliveCount != 0)
            //{
            //    yield return 0;
            //}
            yield return new WaitForSeconds(wave.waveRate);//等待每波之间的时差
        }

        while(enemyAliveCount>0)
        {
            yield return 0;
        }
        Debug.Log("aaaaa");
        Debug.Log(gameObject);
        Gamemanager.Instance.Win();
    }
}

敌人角色脚本

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

public class Enemy1 : MonoBehaviour
{
    private Transform[] positions;
    [SerializeField]private int index = 0;
    [SerializeField]private float speed = 10.0f;
    [SerializeField] private float hp = 200;
    private float totalHp;
    private Slider hpSlider;
    // Start is called before the first frame update
    void Start()
    {
        positions = SwapPoint.positions;
        totalHp = hp;
        hpSlider = GetComponentInChildren<Slider>();
        TurnRotation();
    }

    // Update is called once per frame
    void FixedUpdate()
    {
        Move();
    }

    void Move()
    {
        transform.position = Vector3.MoveTowards(transform.position, positions[index].position, Time.deltaTime * speed);
        //transform.Translate((positions[index].position-transform.position).normalized *Time.deltaTime * speed);
        if (Vector3.Distance(positions[index].position, transform.position) < 0.4f)//到达转换点,去寻找下一个目标点,同时做出相应的旋转
        {
            index++;
            if (index > positions.Length - 1)
            {
                ReachDestination();
                return;
            }
            TurnRotation();
        }

    }
    void TurnRotation()
    {
        Vector3 rot = transform.eulerAngles;
        rot.y += positions[index].transform.eulerAngles.y;
        transform.eulerAngles = rot;
    }

    void ReachDestination()
    {
        Gamemanager.Instance.Failed();
        EnemySpawner.enemyAliveCount--;
        Destroy(this.gameObject);
    }

    void Death()
    {
        EnemySpawner.enemyAliveCount--;
    }

    public void TakeDamage(float damage)
    {
        if (hp < 0) return;
        hp -= damage;
        hpSlider.value = (float)hp / totalHp;
        if(hp  <= 0)
        {
            BuildManager.instance.money += 10;
            EnemySpawner.enemyAliveCount--;
            Destroy(this.gameObject);
        }
    }
}

管理敌人路径

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

public class SwapPoint : MonoBehaviour
{

    public static Transform[] positions;
    // Start is called before the first frame update
    private void Awake()
    {
        positions = new Transform[transform.childCount];
        for(int i =0;i < positions.Length; i++)
        {
            positions[i] = transform.GetChild(i);
        }
    }

    // Update is called once per frame
    void Update()
    {
        
    }
}

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

public class Turret : MonoBehaviour
{

    public List<GameObject> enemys = new List<GameObject>();
    public int attackRateTime = 1;//多少秒攻击一次
    private float timer = 0;//计时器
    public GameObject bulletPrefab;//
    public Transform  firePosition;
    public bool useLaser = false;
    public float damagerate = 60;
    public LineRenderer laserrenderer;
    public GameObject LaserEffect;
    public MapCube mapcube;



    private void OnTriggerEnter(Collider other)
    {
        if(other.tag == "Enemy")
        {
            enemys.Add(other.gameObject);
            if (other.GetComponent<AttackTower>() != null)
            {
                other.GetComponent<AttackTower>().Fire(this.transform);
            }
        }
    }

    private void OnTriggerExit(Collider other)
    {
        if (other.tag == "Enemy")
        {
            enemys.Remove(other.gameObject);
        }
    }
    private void Start()
    {
        firePosition = this.transform.Find("FirePosition");
        timer = attackRateTime;
    }


    private void Update()
    {
        if (useLaser == false)
        {
            timer += Time.deltaTime;
            if (enemys.Count > 0 && timer >= attackRateTime)
            {
                timer = 0f;
                Attack();
            }
        }
        else if(enemys.Count>0)
        {
            if(laserrenderer.enabled == false)
            
                laserrenderer.enabled = true;
                LaserEffect.SetActive(true);
            
            if(enemys[0] == null)
            {
                enemys.RemoveAll(c => c.gameObject == null);
            }
            if(enemys.Count>0)
            {
                laserrenderer.SetPositions(new Vector3[] { firePosition.position, enemys[0].transform.position });
                if(enemys[0].GetComponent<Enemy1>() != null)
                {
                    enemys[0].GetComponent<Enemy1>().TakeDamage(damagerate * Time.deltaTime);
                }
                else
                {
                    enemys[0].GetComponent<Enemy2>().TakeDamage(damagerate * Time.deltaTime);
                }
                LaserEffect.transform.position = enemys[0].transform.position;
                Vector3 pos = transform.position;
                pos.y = enemys[0].transform.position.y;
                LaserEffect.transform.LookAt(pos);
            }
        }
        else
        {
            LaserEffect.SetActive(false);
            laserrenderer.enabled = false;
        }
    }

    void Attack()
    {
        if (enemys[0] == null)
        {
            enemys.RemoveAll(c => c.gameObject == null);
        }
        if(enemys.Count > 0)
        {
            GameObject bullet = GameObject.Instantiate(bulletPrefab, firePosition.position, firePosition.rotation);
            bullet.GetComponent<Bullet>().SetTarget(enemys[0].transform);
        }
    }



    public void RebackMapCube()
    {
        mapcube.isUpgraded = false;
        mapcube.turretGo = null;
        mapcube.turretGoData = null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值