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
| using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Asteroid : MonoBehaviour
{
public GameObject debrisTemplate;
private float initializationTime;
// Start is called before the first frame update
void Start()
{
Rigidbody2D rb = GetComponent<Rigidbody2D>();
//Choose a random angle
float angle = Random.Range(0f, 360f);
this.transform.rotation = Quaternion.Euler(0, 0, angle);
//Choose a random speed
float speed = Random.Range(0.5f, 2f);
Vector3 s = new Vector3(0, speed, 0);
rb.velocity = transform.rotation * s;
initializationTime = Time.timeSinceLevelLoad;
}
// Update is called once per frame
void Update()
{
//Handle screen wrapping
int margin = 50;
//Work out our screen position
Vector2 screenPos = Camera.main.WorldToScreenPoint(transform.position);
//Check if we've moved too far offscreen
if( screenPos.x > Screen.width+margin ){
//off right, move to left
screenPos.x = -margin/2;
}else if( screenPos.x < -margin ){
//off left, move to right
screenPos.x = Screen.width+margin/2;
}
if( screenPos.y > Screen.height+margin ){
//off bottom, move to top
screenPos.y = -margin/2;
}else if( screenPos.y < -margin ){
//off top, move to bottom
screenPos.y = Screen.height+margin/2;
}
//Work out our new world position
Vector3 newPos = Camera.main.ScreenToWorldPoint(screenPos);
transform.position = new Vector2(newPos.x, newPos.y);
}
void OnTriggerEnter2D(Collider2D other)
{
if( Time.timeSinceLevelLoad - initializationTime < 0.5 ){
return;
}
if( other.gameObject.CompareTag("LaserBlast") ){
if( debrisTemplate != null){ // "!=" = "!" + "="
float angle = Random.Range(0f, 180f);
float speed = Random.Range(5f, 10f);
Vector3 s = new Vector3(0, speed, 0);
GameObject a = Instantiate(debrisTemplate,
this.transform.position, this.transform.rotation)
as GameObject;
a.GetComponent<Rigidbody2D>().velocity = a.transform.rotation * s;
GameObject b = Instantiate(debrisTemplate,
this.transform.position, this.transform.rotation * Quaternion.Euler(0, 0, angle))
as GameObject;
b.GetComponent<Rigidbody2D>().velocity = b.transform.rotation * s;
GameObject c = Instantiate(debrisTemplate,
this.transform.position, this.transform.rotation * Quaternion.Euler(0, 0, -angle))
as GameObject;
c.GetComponent<Rigidbody2D>().velocity = c.transform.rotation * s;
}
Destroy(this.gameObject);
Destroy(other.gameObject);
}
}
}
|