zoukankan      html  css  js  c++  java
  • 简单3d RPG游戏 之 004 攻击(一)

    功能:实现点击键盘F键,怪物血量条减少,并且假定是近战,需要对距离进行判断,距离小于一定值的时候按F才会减少怪物的血条。

    新建c#脚本PlayerAttack,绑定到Player,并在unity里将敌人拖动到target属性上。

    public class PlayerAttack : MonoBehaviour {
        public GameObject target;
        // Use this for initialization
        void Start () {
        
        }
        
        // Update is called once per frame
        void Update () {
            if (Input.GetKeyUp (KeyCode.F)) {
                Attack();
            }
        }
    
        private void Attack(){
            EnemyHealth eh = (EnemyHealth)target.GetComponent("EnemyHealth");    
            eh.AddjustCurrentHealth(-10);
        }
    }

    因为之前的EnemyHealth脚本里的AddjustCurrentHealth没有设置public所以存在无法访问该方法,设置一下就好了。
    运行,点击F键,怪物血量条减少10(为了方便调试,先禁止掉Enemy的EnemyAI组件)

    然后走进怪物,在距离差不多的时候计算一下距离,然后用这个距离做限制攻击范围,

    在Attack里添加测试代码

    Debug.WriteLine(Vector3.Distance (target.transform.position, transform.position));
    

    按ctrl+shift+c调出输出窗口,运行查看

    发现距离2的时候就差不多了,那就将2作为近战的距离范围,超过2的时候按F不算攻击。

        private void Attack(){
            if (Vector3.Distance (target.transform.position, transform.position) < 2) {
                EnemyHealth eh = (EnemyHealth)target.GetComponent ("EnemyHealth");    
                eh.AddjustCurrentHealth (-10);
            }
        }
  • 相关阅读:
    如何将数组初始化为全0?
    什么是优先级队列(priority queue)?
    C语言中指针的指针是如何工作的?
    什么是队列(Queue)?
    理解*ptr++
    【Luogu】P4172水管局长(LCT)
    【Luogu】P4159迷路(矩阵优化)
    【Luogu】P3971Alice And Bob(贪心)
    【Luogu】P3211XOR和路径(高斯消元)
    【Luogu】P2445动物园(最大流)
  • 原文地址:https://www.cnblogs.com/rentianlong/p/3629820.html
Copyright © 2011-2022 走看看