以下腳本均來自siki學院的教學視頻,個人感覺非常有用,記錄下來留著以后溫習
Enemy朝向Player并向Player方向移動(2D拾荒者[敵人腳本]):
public class Enemy : MonoBehaviour
{
private Vector2 targetPosition;
private Transform player;
private Rigidbody2D rigidbody;
public float smoothing = 3;
public int lossFood = 10;
public AudioClip attackAudio;
private BoxCollider2D collider;
private Animator animator;
void Start()
{
player = GameObject.FindGameObjectWithTag("Player").transform;
rigidbody = GetComponent<Rigidbody2D>();
collider = GetComponent<BoxCollider2D>();
animator = GetComponent<Animator>();
targetPosition = transform.position;
GameManager.Instance.enemyList.Add(this);
}
void Update()
{
rigidbody.MovePosition( Vector2.Lerp(transform.position, targetPosition, smoothing * Time.deltaTime));
}
public void Move()
{
Vector2 offset = player.position - transform.position;//主角位置減當前位置
if (offset.magnitude < 1.1f)//偏移的大小
{
//攻擊(Enemy和Player位置相鄰時Enemy可以攻擊Player)
animator.SetTrigger("Attack");
AudioManager.Instance.RandomPlay(attackAudio);
player.SendMessage("TakeDamage",lossFood);
}
else
{
float x= 0,y=0;
if (Mathf.Abs(offset.y) > Mathf.Abs(offset.x))
{
//按照y軸移動
if (offset.y < 0)
{
y = -1;
}
else//y的正軸
{
y = 1;
}
}
else
{
//按照x軸移動
if (offset.x > 0)
{
x = 1;
}
else
{
x = -1;
}
}
//設定目標位置之前先做檢測(以下內容為檢測Enemy前方是否有障礙物)
collider.enabled = false;
RaycastHit2D hit = Physics2D.Linecast(targetPosition, targetPosition + new Vector2(x,y));
collider.enabled = true;
if (hit.transform == null)//前方沒有任何物體或前方是食物時才能移動
{
targetPosition += new Vector2(x, y);
}
else
{
if (hit.collider.tag == "Food" || hit.collider.tag == "Suda")
{
targetPosition += new Vector2(x, y);
}
}
}
}
}
Bullet追蹤Enemy(塔防游戲[子彈腳本]):
private Transform target;//定義傳送目標
public void SetTarget(Transform _target)
{
this.target = _target;
}
void Update()
{
transform.LookAt(target.position);
transform.Translate(Vector3.forward * speed * Time.deltaTime);
}
記得設定子彈攻擊的目標
目前只使用過這兩種腳本,如果再用應用到的物體跟蹤目標腳本會繼續補上,也歡迎大佬們補充
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/287697.html
標籤:其他
下一篇:2021-06-14
