Files

80 lines
2.2 KiB
C#
Raw Permalink Normal View History

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class EnemyScript : MonoBehaviour
{
2020-07-12 01:34:47 -04:00
public GameObject particleEffect;
2020-07-12 01:07:52 -04:00
public AudioClip[] spawnSounds;
public AudioClip[] defeatSounds;
2020-07-11 11:23:39 -04:00
private float speed;
private GameObject player;
private Vector2 movement;
private Rigidbody2D rb;
private Animator animator;
2020-07-12 01:07:52 -04:00
private AudioSource audioSource;
private Vector3 previousPosition;
private Vector3 currentMovementDirection;
void Start()
{
rb = GetComponent<Rigidbody2D>();
animator = GetComponent<Animator>();
2020-07-12 01:07:52 -04:00
audioSource = GetComponent<AudioSource>();
player = GameObject.FindWithTag("Player");
2020-07-11 11:23:39 -04:00
speed = Random.Range(0.5f, 3.0f);
2020-07-12 01:07:52 -04:00
audioSource.clip = spawnSounds[Random.Range(0,spawnSounds.Length)];
audioSource.Play();
}
// Update is called once per frame
void Update()
{
movement = rb.velocity;
if(player != null)
{
transform.position = Vector2.MoveTowards(
transform.position, player.transform.position, speed * Time.deltaTime);
}
if(previousPosition != transform.position) {
currentMovementDirection = (transform.position - previousPosition);
previousPosition = transform.position;
}
animator.SetFloat("Horizontal", currentMovementDirection.y);
animator.SetFloat("Vertical", currentMovementDirection.x);
animator.SetBool("Speed", true);
}
void OnCollisionEnter2D(Collision2D other)
{
2020-07-11 16:19:57 -04:00
if(other.gameObject.tag == "Bullet")
{
PlayerPrefs.SetInt("Score", PlayerPrefs.GetInt("Score")+1);
2020-07-12 01:07:52 -04:00
AudioSource.PlayClipAtPoint(
defeatSounds[Random.Range(0,defeatSounds.Length)], new Vector3(0, 0, 0));
2020-07-12 01:34:47 -04:00
Instantiate(particleEffect, transform.position, transform.rotation);
2020-07-11 16:19:57 -04:00
Destroy(gameObject);
}
if(other.gameObject.tag == "Player")
{
2020-07-12 01:07:52 -04:00
AudioSource.PlayClipAtPoint(
defeatSounds[Random.Range(0,defeatSounds.Length)], new Vector3(0, 0, 0));
2020-07-12 01:34:47 -04:00
Instantiate(particleEffect, transform.position, transform.rotation);
Destroy(gameObject);
}
animator.SetBool("Speed", false);
}
}