unity小项目主角打击怪物

来源:互联网 发布:管家婆erp软件 编辑:程序博客网 时间:2024/05/02 02:01

欢迎来到unity学习社区

 

 

今天的内容是主角打击怪物的功能

 

 一、功能及界面设置


首先需要给怪物和主角兵器添加碰撞组件 并勾选Is Trigger 属性

 

 

其次 给怪物添加刚体并去掉重力属性

 

 

主角需要具备一些必要的动画效果(如 禁止 走 跑 跳 攻击等)

 

 

二、添加相应的脚本了 废话不多说 代码如下:

 

 

主角代码:

 

 

using UnityEngine;

using System.Collections;

 

public class Hero : MonoBehaviour {

    private NavMeshAgent agent;

    public GameObject hero;

    float smooth;

    public static bool flag=false ;

    public static  float lifetime=0;

  

void Start () {

agent =GetComponent <NavMeshAgent >();

}

void Update () {

if(Input .GetMouseButton (0)){

        RaycastHit hit;

        Ray ray = Camera.main.ScreenPointToRay(Input .mousePosition );

        if(Physics .Raycast (ray,out hit)){

            agent.SetDestination(hit.point );

           }

        }

}

 

    void LateUpdate()

{

//调用主角动画中的攻击 禁止 走的 动画特效

        if (Input.GetKey(KeyCode.Q))

        {

            hero.transform.animation.Play("Skill");

            print("aaaaaaa");

        }

         else if (Input.GetKey(KeyCode.W))

        {

            hero.transform.animation.Play("Attack00");

            print("bbbbb");

        }

        else if (Input.GetKey(KeyCode.E))

        {

            hero.transform.animation.Play("Attack01");

        }

        else  if (Input.GetKey(KeyCode.R))

        {

            hero.transform.animation.Play("Attack");

        }

        else if (agent.remainingDistance == 0)

        {

            

            OnAnimationToidle();

          

        }

        else

        {

            OnAnimationToWalk();

        }

    }

    void OnAnimationToidle() {

             hero.transform.animation.Play("Idle");

    }

    void OnAnimationToWalk()

    {

            hero.transform.animation.Play("Walk");

     

    }

    void OnAnimationToKill()

    {

              hero.transform.animation.Play("Attack00");

       }

}

 

怪物代码:

 

 

using UnityEngine;

using System.Collections;

 

public class Monster : MonoBehaviour {

    private float life = 6;

    void OnTriggerEnter(Collider col)

    {

        if (col.CompareTag("Sword"))

        //if (col.CompareTag("Dwarf")) 另一种获得标签的方式

        {

            life--;

            if(life<=0){

            Destroy(this.gameObject);

            Hero.lifetime++;

            } 

        }

    }

    

}

 

0 0