【unity2D横板】【sunnyland】敌人巡逻追击主角以及返回原点

您所在的位置:网站首页 《跟踪追击》 【unity2D横板】【sunnyland】敌人巡逻追击主角以及返回原点

【unity2D横板】【sunnyland】敌人巡逻追击主角以及返回原点

2024-07-12 05:53| 来源: 网络整理| 查看: 265

今天研究了一下午,总算把这个小鸟的逻辑给做出来了

用了Math.Pow(x,y),这是C#中用来求数字的幂的方法

还有Vector2.MoveTowards方法。

小鸟的逻辑是,自动巡逻,在侦察范围内发现主角则会一直追击主角逃出追击范围为止

假设逃出追击范围并且小鸟出界,那么它则往原点飞

我设置了三个状态

巡逻,追击,返回原点

看代码吧

using System; using System.Collections; using System.Collections.Generic; using UnityEngine; public class eagleController : MonoBehaviour { // Start is called before the first frame update public float speed = 3.0f; public float changeTime = 3.0f; float Timer; float direction = 1; Animator animator; public GameObject Player = null;//这里来存放主角对象 private float XBorder;//X边界 private float YBorder;//Y边界 private bool discoverable;//发现主角 private bool outside;//出界 public float radial;//边界半径 Vector2 origin; void Start() { Timer = changeTime; animator = GetComponent(); origin = transform.position;//存放原点 XBorder = origin.x + radial; YBorder = origin.y; } // Update is called once per frame void Update() { Rigidbody2D playerRigid = Player.GetComponent(); Vector2 beforePosition = transform.position; if (Math.Pow(playerRigid.position.x - transform.position.x, 2) + Math.Pow(playerRigid.position.y - transform.position.y, 2) origin.x + XBorder || transform.position.x < origin.x - XBorder || transform.position.y > origin.y + YBorder || transform.position.y < origin.y - YBorder)//巡逻边界 { outside = true; } flyOrigin(origin, Time.deltaTime); flyNormal(); Vector2 currentPosition = transform.position; animator.SetFloat("fly", currentPosition.x - beforePosition.x ); } private void OnCollisionEnter2D(Collision2D other) { foxcontroller fox = other.gameObject.GetComponent(); if (fox != null) { fox.ChangeHealth(-1); } } private void flyNormal()//巡逻姿态 { if (discoverable||outside) { return; } Vector2 position = transform.position; Timer -= Time.deltaTime; position.x = position.x + direction * Time.deltaTime * speed; transform.position = position; if (Timer < 0) { Timer = changeTime; direction = -direction; } animator.SetFloat("fly", direction);//动画控制 } public void flyAttack(float dt,Rigidbody2D playerRigid)//攻击姿态 { float quickSpeed = speed * 3; transform.position = Vector2.MoveTowards(transform.position, playerRigid.position, quickSpeed*dt); //Debug.Log(Math.Pow(playerRigid.position.x - transform.position.x, 2)); } public void flyOrigin(Vector2 origin,float dt)//出界返回原点 { if (discoverable||!outside) { return; } transform.position = Vector2.MoveTowards(transform.position,origin , speed * dt); if (transform.position.x == origin.x && transform.position.y == origin.y) { outside = false; } } }

 返回原点以及巡逻

 追击

 



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3