1
0
Fork 0
Bildschirmflausch-LD41/Assets/Scripts/Entities/Enemy.cs

77 lines
2.8 KiB
C#
Raw Normal View History

using System;
using System.Collections.Generic;
using UnityEngine;
using Assets.Scripts.Entities.Attack;
namespace Assets.Scripts.Entities {
public class Enemy : Mob {
[SerializeField]
private float speed = 1;
[SerializeField]
private float rotationSpeed = 1;
2018-04-23 00:25:37 +02:00
[SerializeField]
protected GameObject victim;
2018-04-23 00:25:37 +02:00
[SerializeField]
private Rigidbody2D body;
2018-04-23 00:25:37 +02:00
private float nextAttackTime;
public Enemy(int mHP) : base(mHP) {
}
2018-04-23 20:19:12 +02:00
protected virtual void Start() {
2018-04-23 22:27:46 +02:00
ParticleSystem[] pss = GetComponentsInChildren<ParticleSystem>();
foreach(ParticleSystem ps in pss) {
if ( ps.gameObject.name == "spawn" ) {
ps.Play();
}
2018-04-23 20:19:12 +02:00
}
if ( objective != null ) {
Player ply = objective.GetPlayer();
if ( ply != null )
victim = ply.gameObject;
}
if (attack != null)
nextAttackTime = Time.timeSinceLevelLoad + attack.GetCooldownTime() * (UnityEngine.Random.value + 0.5f);
2018-04-23 20:19:12 +02:00
}
void Update() {
if ( victim == null || attack == null ) {
if ( objective != null ) {
Player ply = objective.GetPlayer();
if ( ply != null )
victim = ply.gameObject;
}
return;
}
if ( Time.timeSinceLevelLoad >= nextAttackTime ) {
2018-04-23 01:25:50 +02:00
RaycastHit2D[] hits = Physics2D.RaycastAll(transform.position, transform.localRotation * Vector3.up, attack.GetRange());
List<RaycastHit2D> rh = new List<RaycastHit2D>(hits);
RaycastHit2D hit = rh.Find(x => x.fraction != 0);
if ( hit.collider != null && hit.collider.gameObject == victim ) {
Debug.Log("Attacking Player!!!");
attack.Attack();
nextAttackTime = Time.timeSinceLevelLoad + attack.GetCooldownTime() * (UnityEngine.Random.value + 0.25f);
}
}
Vector3 distanceToEnemy = victim.transform.position - gameObject.transform.position;
2018-04-23 00:35:32 +02:00
//rotation
Vector3 localRotation = gameObject.transform.localRotation * Vector3.up;
float angleToRotate = Mathf.Round(Vector3.SignedAngle(localRotation, distanceToEnemy.normalized, Vector3.forward));
gameObject.transform.Rotate(0, 0, angleToRotate * rotationSpeed);
2018-04-23 00:35:32 +02:00
if ( distanceToEnemy.magnitude < attack.GetRange() ) {
return;
}
// movement
body.velocity = new Vector2(distanceToEnemy.normalized.x, distanceToEnemy.normalized.y) * speed;
2018-04-23 00:35:32 +02:00
}
}
}