/
AlienMovement.cs
90 lines (78 loc) · 2.45 KB
/
AlienMovement.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class AlienMovement : MonoBehaviour
{
public GameObject energy;
public GameObject projectile;
private float xRange;
private float yRange;
private float xMoving;
private float yMoving;
private float speed;
private float timerShoot;
private float shootCooldown;
void Start()
{
xRange = 8;
yRange = 5;
speed = 0.08f;
shootCooldown = Random.Range(1.0f, 2.5f);
if (transform.position.x >= xRange) {
xMoving = -1;
}
else if (transform.position.x <= -xRange) {
xMoving = 1;
}
else {
xMoving = 0;
}
if (transform.position.y >= yRange) {
yMoving = -1;
}
else if (transform.position.y <= -yRange) {
yMoving = 1;
}
else {
yMoving = 0;
}
}
void Update()
{
timerShoot += Time.deltaTime;
if (timerShoot >= shootCooldown) {
ShootAtPlayer();
timerShoot = 0;
}
CheckOutOfBounds();
}
void FixedUpdate()
{
transform.position = new Vector2(transform.position.x + xMoving * speed, transform.position.y + yMoving * speed);
}
private void CheckOutOfBounds()
{
if ( (Mathf.Abs(transform.position.x) > xRange + 3) || (Mathf.Abs(transform.position.y) > yRange + 1) ) {
Destroy(gameObject);
}
}
private void ShootAtPlayer()
{
// find the angle between the alien ship and the player
if (GameObject.Find("Player(Clone)")) {
PlayerController player = GameObject.Find("Player(Clone)").GetComponent<PlayerController>();
float x = player.transform.position.x - transform.position.x;
float y = player.transform.position.y - transform.position.y;
float angle = Mathf.Atan2(x, y) * Mathf.Rad2Deg * -1;
Instantiate(projectile, transform.position, Quaternion.Euler(new Vector3(0, 0, angle)));
}
}
private void OnTriggerEnter2D(Collider2D other)
{
if (other.gameObject.CompareTag("Player_Projectile")) {
Instantiate(energy, transform.position, energy.transform.rotation);
Destroy(other.gameObject);
Destroy(gameObject);
}
}
}