Unity_Fps射击游戏自动瞄准下一个敌人功能

 private void Awake()
    {
       
       Instance = this;
        

        this.InitializeAim();

    }

    private void Update()
    {
       
        this.UpdateAim();
    }
    
     
      
       
        
         
     /// <summary>
    /// 初始化自瞄
    /// </summary>
    private void InitializeAim()
    {
        this.AllTargets = new List<IPlayerWeaponTarget>();
       
        GameMessenger.AddEventListener<IPlayerWeaponTarget>("PWTSpawned", delegate (IPlayerWeaponTarget t)
        {
            this.AllTargets.Add(t);
        });
        GameMessenger.AddEventListener<IPlayerWeaponTarget>("PWTDespawned", delegate (IPlayerWeaponTarget t)
        {
            this.AllTargets.Remove(t);
        });
    }
    
     /// <summary>
    /// 更新目标
    /// </summary>
    private void UpdateAim()
    {
        //判断下是否拥有武器
        if (!this.HasCurrentWeapon)
        {
            return;
        }
        //判断下List是否有元素

        if (!this.AllTargets.Any<IPlayerWeaponTarget>())
        {   //当前的目标为空
            this.CurrentAimTarget = null;
            return;
        }
        this.CurrentAimTarget = null;
        float num = 0f;
        //遍历list里的目标
        for (int i = 0; i < this.AllTargets.Count; i++)
        {    
            IPlayerWeaponTarget playerWeaponTarget = this.AllTargets[i];
            //获得与玩家的距离
            float approximateDistanceFromPlayer = playerWeaponTarget.GetApproximateDistanceFromPlayer();
            //是否在玩家前面
            if (playerWeaponTarget.IsAheadFromPlayer()
             && playerWeaponTarget.CamAimTo() 
             //获取目标和目标圆之间的平方距离 小于瞄准圆屏幕位置
             && this.GetSqrMagnitudeBetweenTargetAndAimCircle(playerWeaponTarget) < this.AimCircleRadiusAbsoluteSqr
             //最大瞄准距离大于与玩家的距离
             && this.CurrentWeapon.MaxAimDistance > approximateDistanceFromPlayer 
             //当前目标 或者玩家的距离小于0
             && (this.CurrentAimTarget == null || approximateDistanceFromPlayer < num))
            {     //当前的目标等于    获取目标  tram
                this.CurrentAimTarget = playerWeaponTarget.GetPlayerAimTarget();
                //跟新最近距离
                 num = approximateDistanceFromPlayer;
            }
        }
    }
     /// <summary>
    /// 瞄准圆屏幕位置
    /// </summary>
    public Vector2 AimCircleScreenPosition
    {
        get
        {
            float num = (float)PlayerMainCameraSystem.Instance.MainCamera.pixelWidth / 2f;
            float y = (float)PlayerMainCameraSystem.Instance.MainCamera.pixelHeight / 2f;
            float num2 = 0f;
            if (PlayerMovementSystem.Instance.XMovementState != PlayerMovementSystem.PlayerXMovementState.None)
            {
                num2 = (float)((PlayerMovementSystem.Instance.XMovementState == PlayerMovementSystem.PlayerXMovementState.MoveLeft) ? -1 : 1) * (this.GetAbsoluteWidthForAim(this.AimCircleMaxCenterOffset) * PlayerInputSystem.Instance.CurrentDirectionGestureXMultiplier);
            }
            return new Vector2(num + num2, y);
        }
    }
    
    /// <summary>
    /// 获取目标和目标圆之间的平方距离
    /// </summary>
    /// <param name="target"></param>
    /// <returns></returns>
    private float GetSqrMagnitudeBetweenTargetAndAimCircle(IPlayerWeaponTarget target)
    {
        Vector2 aimTargetScreenSpacePosition = target.GetAimTargetScreenSpacePosition();
        return (this.AimCircleScreenPosition - aimTargetScreenSpacePosition).sqrMagnitude;
    }
    
    
    
     /// <summary>
    /// 获取范围内的目标
    /// </summary>
    /// <param name="origin"></param>
    /// <param name="r"></param>
    /// <returns></returns>
    public IEnumerable<IPlayerWeaponTarget> GetTargetsInRange(Vector3 origin, float r)
    {
        float rr = r * r;
        return from t in this.AllTargets
               where (t.GetPlayerAimTarget().position - origin).sqrMagnitude < rr
               select t;
    }
    
    
    
    
    
    
    /// <summary>
    /// 处理武器射击
    /// </summary>
    private void HandleWeaponFire()
    {    //调度武器伤害
        this.DispatchWeaponDamage(this.CurrentAimTarget);
        if (this.CurrentWeapon.MultikillRadius > 0f && this.CurrentAimTarget != null)
        {
            IEnumerable<IPlayerWeaponTarget> enumerable = 
            from t in this.AllTargets
            where t.GetPlayerAimTarget() != this.CurrentAimTarget &&
            (t.GetPlayerAimTarget().position - this.CurrentAimTarget.position).sqrMagnitude
            < this.CurrentWeapon.MultikillRadius * this.CurrentWeapon.MultikillRadius
            select t;
            int num = 0;
            foreach (IPlayerWeaponTarget playerWeaponTarget in enumerable)
            {
                if (num > this.CurrentWeapon.MaxMultikills)
                {
                    break;
                }
                this.DispatchWeaponDamage(playerWeaponTarget.GetPlayerAimTarget());
                num++;
            }
        }
        if (!this.IsFiredInThisRun)
        {
            this.IsFiredInThisRun = true;
           Debug.Log("PlayerFirstFireInRun");
        }
    }
    
    
    
    /// <summary>
    /// 调度武器伤害
    /// </summary>
    /// <param name="target"></param>
    private void DispatchWeaponDamage(Transform target)
    {
        if (target == null)
        {
            return;
        }
        float time = Vector3.Distance(base.transform.position, target.position) / this.CurrentWeapon.MaxAimDistance;
        float num = this.CurrentWeapon.FireDamageDistanceFactor.Evaluate(time);
        float hitDamage = this.CurrentWeapon.PrevFireDamage * num;
        PlayerWeaponDamageInfo playerWeaponDamageInfo = new PlayerWeaponDamageInfo(target, hitDamage);
        IPlayerWeaponTarget asWeaponTarget = playerWeaponDamageInfo.AsWeaponTarget;
        if (asWeaponTarget != null)
        {
            asWeaponTarget.ReceiveDamage(playerWeaponDamageInfo);
        }
        GameMessenger.Broadcast<PlayerWeaponDamageInfo>("PlayerWeaponDamageDispatched", playerWeaponDamageInfo);
    }

sing System;
using UnityEngine;
public interface IPlayerWeaponTarget
{/// <summary>
/// 受到伤害
/// </summary>
/// <param name="damage"></param>
    void ReceiveDamage(PlayerWeaponDamageInfo damage);
    /// <summary>
    /// 获取目标
    /// </summary>
    /// <returns></returns>
    Transform GetPlayerAimTarget();

    bool CamAimTo();
}
using System;

using UnityEngine;
//玩家武器目标扩展
public static class PlayerWeaponTargetExtensions
{
    public static bool IsZombie(this IPlayerWeaponTarget target)
    {
        return target is ZombieController;
    }

    public static ZombieController AsZombie(this IPlayerWeaponTarget target)
    {
        return target as ZombieController;
    }


    // 计算玩家到目标的角度

    public static float CalculateAngleFromPlayerToTarget(this IPlayerWeaponTarget target, bool fixBigZombieAngleOffset = true)
    {
        ZombieController zombieController = target.AsZombie();
      float num = 1f;
      if (zombieController != null && fixBigZombieAngleOffset && zombieController.IsBig)
       {
          num = zombieController.transform.localScale.x;
           zombieController.transform.localScale = new Vector3(zombieController.DefaultScale, zombieController.DefaultScale, zombieController.DefaultScale);
       }
       Vector3 to = target.GetPlayerAimTarget().position - PlayerController.Instance.transform.position;
      if (zombieController != null && fixBigZombieAngleOffset && zombieController.IsBig)
       {
           zombieController.transform.localScale = new Vector3(num, num, num);
      }
      to.Normalize();
        return Mathf.Abs(Vector3.Angle(PlayerController.Instance.transform.forward, to));
   }

    /// <summary>
    /// 在球员前面
    /// </summary>
    /// <param name="target"></param>
    /// <returns></returns>
    public static bool IsAheadFromPlayer(this IPlayerWeaponTarget target)
    {
        //position.z  方法待考证
        return target.GetPlayerAimTarget().transform.position.z >= PlayerController.Instance.transform.position.z;
    }

    /// <summary>
    /// 获取目标屏幕空间位置
    /// </summary>
    /// <param name="target"></param>
    /// <returns></returns>
    public static Vector2 GetAimTargetScreenSpacePosition(this IPlayerWeaponTarget target)
    {
        return PlayerMainCameraSystem.Instance.MainCamera.WorldToScreenPoint(target.GetPlayerAimTarget().position);
    }

    /// <summary>
    /// 与玩家保持大致距离
    /// </summary>
    /// <param name="target"></param>
    /// <returns></returns>
    public static float GetApproximateDistanceFromPlayer(this IPlayerWeaponTarget target)
    {
        return Mathf.Abs
            (PlayerController.Instance.transform.position.z
            - target.GetPlayerAimTarget().position.z);
    }

}
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,793评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 87,567评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,342评论 0 338
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,825评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,814评论 5 368
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,680评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,033评论 3 399
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,687评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 42,175评论 1 300
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,668评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,775评论 1 332
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,419评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,020评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,978评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,206评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,092评论 2 351
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,510评论 2 343

推荐阅读更多精彩内容