aboutsummaryrefslogtreecommitdiff
path: root/Assets/Scripts/Crawler.cs
diff options
context:
space:
mode:
authorTom Harley2018-09-03 23:34:21 +0100
committerTom Harley2018-09-03 23:36:01 +0100
commit5440734d820606b29a795c46172ade5d7eba8efb (patch)
tree85867f40afb02cfa2a5028b515ed0a195866b7e9 /Assets/Scripts/Crawler.cs
downloadpowerless-5440734d820606b29a795c46172ade5d7eba8efb.tar.gz
powerless-5440734d820606b29a795c46172ade5d7eba8efb.zip

Initial commit

Diffstat (limited to 'Assets/Scripts/Crawler.cs')
-rw-r--r--Assets/Scripts/Crawler.cs51
1 files changed, 51 insertions, 0 deletions
diff --git a/Assets/Scripts/Crawler.cs b/Assets/Scripts/Crawler.cs
new file mode 100644
index 0000000..3b13f24
--- /dev/null
+++ b/Assets/Scripts/Crawler.cs
@@ -0,0 +1,51 @@
+using System.Collections;
+using System.Collections.Generic;
+using UnityEngine;
+
+public class Crawler : MonoBehaviour {
+ public Vector2 velocity = new Vector2(1, 0);
+
+ public float raycastLength = 0.1f;
+
+ private BoxCollider2D coll;
+ private Rigidbody2D body;
+
+ void Start() {
+ coll = GetComponent<BoxCollider2D>();
+ body = GetComponent<Rigidbody2D>();
+
+ body.velocity = velocity;
+ }
+
+ void FixedUpdate() {
+ Vector2 bounds = coll.bounds.extents;
+
+ RaycastHit2D leftHit = Physics2D.Raycast(
+ transform.position + Vector3.left * bounds.x + Vector3.down * bounds.y,
+ Vector2.down, raycastLength);
+
+ RaycastHit2D rightHit = Physics2D.Raycast(
+ transform.position + Vector3.right * bounds.x + Vector3.down * bounds.y,
+ Vector2.down, raycastLength);
+
+ Debug.DrawRay(
+ transform.position + Vector3.left * bounds.x + Vector3.down * bounds.y,
+ Vector2.down, Color.blue);
+
+ Debug.DrawRay(
+ transform.position + Vector3.right * bounds.x + Vector3.down * bounds.y,
+ Vector2.down, Color.red);
+
+ if (!leftHit || !rightHit) {
+ Flip();
+ }
+ }
+
+ void Flip() {
+ body.velocity = -body.velocity;
+ }
+
+ void Update() {
+ transform.localScale = new Vector2(Mathf.Sign(body.velocity.x), 1);
+ }
+}