From 3c9bc548c19691d431efcb29c31d78bff7ce79cf Mon Sep 17 00:00:00 2001 From: Jordan Orelli Date: Fri, 17 Apr 2020 22:20:36 -0500 Subject: [PATCH] horizontal collisions --- Assets/Scripts/MoveController.cs | 25 +++++++++++++++++++++++-- Assets/Scripts/PlayerController.cs | 3 +++ 2 files changed, 26 insertions(+), 2 deletions(-) diff --git a/Assets/Scripts/MoveController.cs b/Assets/Scripts/MoveController.cs index 3073d9b..6c0b3a8 100644 --- a/Assets/Scripts/MoveController.cs +++ b/Assets/Scripts/MoveController.cs @@ -25,7 +25,12 @@ public class MoveController : MonoBehaviour public void Move(Vector3 velocity) { UpdateRaycastOrigins(); - VerticalCollisions(ref velocity); + if (velocity.x != 0) { + HorizontalCollisions(ref velocity); + } + if (velocity.y != 0) { + VerticalCollisions(ref velocity); + } transform.Translate(velocity); } @@ -37,13 +42,29 @@ public class MoveController : MonoBehaviour Vector2 rayOrigin = (directionY > 0) ? raycastOrigins.topLeft : raycastOrigins.bottomLeft; rayOrigin += Vector2.right * (verticalRaySpacing * i + velocity.x); + Debug.DrawRay(rayOrigin, Vector2.up * directionY * rayLength, Color.red); RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.up * directionY, rayLength, collisionMask); if (hit) { velocity.y = (hit.distance - skinWidth) * directionY; rayLength = hit.distance; } + } + } + + private void HorizontalCollisions(ref Vector3 velocity) { + float directionX = Mathf.Sign(velocity.x); // -1 for left, 1 for right + float rayLength = Mathf.Abs(velocity.x) + skinWidth; - Debug.DrawRay(raycastOrigins.bottomLeft + Vector2.right * verticalRaySpacing * i, Vector2.up * -2, Color.red); + for (int i = 0; i < horizontalRayCount; i++) { + Vector2 rayOrigin = (directionX > 0) ? raycastOrigins.bottomRight : raycastOrigins.bottomLeft; + rayOrigin += Vector2.up * (horizontalRaySpacing * i); + + Debug.DrawRay(rayOrigin, Vector2.right * directionX * rayLength, Color.red); + RaycastHit2D hit = Physics2D.Raycast(rayOrigin, Vector2.right * directionX, rayLength, collisionMask); + if (hit) { + velocity.x = (hit.distance - skinWidth) * directionX; + rayLength = hit.distance; + } } } diff --git a/Assets/Scripts/PlayerController.cs b/Assets/Scripts/PlayerController.cs index 94e7637..96b6a40 100644 --- a/Assets/Scripts/PlayerController.cs +++ b/Assets/Scripts/PlayerController.cs @@ -6,6 +6,7 @@ using UnityEngine; public class PlayerController : MonoBehaviour { public float gravity = -20f; + public float moveSpeed = 6f; private Vector3 velocity; private MoveController moveController; @@ -15,6 +16,8 @@ public class PlayerController : MonoBehaviour { } void Update() { + Vector2 input = new Vector2(Input.GetAxisRaw("Horizontal"), Input.GetAxisRaw("Vertical")); + velocity.x = input.x * moveSpeed; velocity.y += gravity * Time.deltaTime; moveController.Move(velocity * Time.deltaTime); }