From 5440734d820606b29a795c46172ade5d7eba8efb Mon Sep 17 00:00:00 2001 From: Tom Harley Date: Mon, 3 Sep 2018 23:34:21 +0100 Subject: Initial commit --- Assets/Scripts/Crawler.cs | 51 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 51 insertions(+) create mode 100644 Assets/Scripts/Crawler.cs (limited to 'Assets/Scripts/Crawler.cs') 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(); + body = GetComponent(); + + 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); + } +} -- cgit v1.2.1