From 483fbf510e13bc3d06dda12bd091165f0f7e8154 Mon Sep 17 00:00:00 2001 From: Jordan Orelli Date: Fri, 17 Apr 2020 22:26:44 -0500 Subject: [PATCH] zero out velocities on collisions --- Assets/Scripts/MoveController.cs | 27 +++++++++++++++++++++++++++ Assets/Scripts/PlayerController.cs | 7 +++++++ 2 files changed, 34 insertions(+) diff --git a/Assets/Scripts/MoveController.cs b/Assets/Scripts/MoveController.cs index 6c0b3a8..37bb318 100644 --- a/Assets/Scripts/MoveController.cs +++ b/Assets/Scripts/MoveController.cs @@ -11,6 +11,7 @@ public class MoveController : MonoBehaviour public int horizontalRayCount = 4; public int verticalRayCount = 4; public LayerMask collisionMask; + public CollisionInfo collisions; private float horizontalRaySpacing; private float verticalRaySpacing; @@ -25,6 +26,8 @@ public class MoveController : MonoBehaviour public void Move(Vector3 velocity) { UpdateRaycastOrigins(); + collisions.Reset(); + if (velocity.x != 0) { HorizontalCollisions(ref velocity); } @@ -45,6 +48,11 @@ public class MoveController : MonoBehaviour Debug.DrawRay(rayOrigin, Vector2.up * directionY * rayLength, Color.red); RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up * directionY, rayLength, collisionMask); if (hit) { + if (directionY > 0) { + collisions.above = true; + } else { + collisions.below = true; + } velocity.y = (hit.distance - skinWidth) * directionY; rayLength = hit.distance; } @@ -62,6 +70,11 @@ public class MoveController : MonoBehaviour Debug.DrawRay(rayOrigin, Vector2.right * directionX * rayLength, Color.red); RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, collisionMask); if (hit) { + if (directionX > 0) { + collisions.right = true; + } else { + collisions.left = true; + } velocity.x = (hit.distance - skinWidth) * directionX; rayLength = hit.distance; } @@ -99,4 +112,18 @@ public class MoveController : MonoBehaviour public Vector2 bottomLeft; public Vector2 bottomRight; } + + public struct CollisionInfo { + public bool above; + public bool below; + public bool left; + public bool right; + + public void Reset() { + above = false; + below = false; + left = false; + right = false; + } + } } diff --git a/Assets/Scripts/PlayerController.cs b/Assets/Scripts/PlayerController.cs index 96b6a40..795e552 100644 --- a/Assets/Scripts/PlayerController.cs +++ b/Assets/Scripts/PlayerController.cs @@ -16,6 +16,13 @@ public class PlayerController : MonoBehaviour { } void Update() { + if (moveController.collisions.below || moveController.collisions.above) { + velocity.y = 0; + } + if (moveController.collisions.left || moveController.collisions.right) { + velocity.x = 0; + } + Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")); velocity.x = input.x * moveSpeed; velocity.y += gravity * Time.deltaTime;