Since i’m just starting to learn how to use #C i’ve been using a youtube playlist that teachs how to make a 2D game by using a 2DBoxCollider and raycasts for the player as a reference point to start doing my own stuff.
So now i’m doing a Physics script to use with any kind of mobile object in a 2d game, and the first thing i’m doing are the raycast. Since i want my game object to rotate to mach an angle when its above one, the raycast should do the same, but that didn’t happed in the way i was expecting.
Right now i’ve manage to fix the greatest part of the issues in a separate object without physics and now i’m just left with one problem and it’s this:
The red rays are how i started, and the green ones are what i got after fixing most of the errors.
So, i don’t know if is notizable, but the rays’ origin try to match the starting position of the collider instead of matching the new position. If someone know how to fixs this, i would like to know.
Here’s the code of the green rays for anyone that want to check it out (hopefully i deleted the right things from the red rays)
[RequireComponent(typeof(BoxCollider2D))]
public class MainController2D : MonoBehaviour
{
public LayerMask collisionMask; //separates objects from diferent layers to know wich ones to focus on
const float skinWidth = 0.015f;
new BoxCollider2D collider;
RaycastOrigins raycastOrigins;
private void Start()
{
collider = GetComponent<BoxCollider2D>();
}
private void Update()
{
UpdateRaycastOrigins();
Debug.DrawRay(transform.TransformPoint(raycastOrigins.top + raycastOrigins.left), transform.TransformDirection (Vector3.up * 2), Color.green );
Debug.DrawRay(transform.TransformPoint(raycastOrigins.top + raycastOrigins.right), transform.TransformDirection(Vector3.up * 2), Color.green);
Debug.DrawRay(transform.TransformPoint(raycastOrigins.bottom + raycastOrigins.left), transform.TransformDirection(Vector3.down * 2), Color.green);
Debug.DrawRay(transform.TransformPoint(raycastOrigins.bottom + raycastOrigins.right), transform.TransformDirection(Vector3.down * 2), Color.green);
Debug.DrawRay(transform.TransformPoint(raycastOrigins.right + (raycastOrigins.bottom / 3)), transform.TransformDirection(Vector3.right * 2), Color.green);
Debug.DrawRay(transform.TransformPoint(raycastOrigins.left + (raycastOrigins.bottom / 3)), transform.TransformDirection(Vector3.left * 2), Color.green);
}
private void UpdateRaycastOrigins()
{
Bounds bounds = collider.bounds;
bounds.Expand(skinWidth * -2);
raycastOrigins.top = new Vector3(0, bounds.extents.y);
raycastOrigins.bottom = new Vector3(0, -bounds.extents.y);
raycastOrigins.left = new Vector3(-bounds.extents.x,0);
raycastOrigins.right = new Vector3(bounds.extents.x,0);
}
struct RaycastOrigins
{
public Vector3 top, bottom;
public Vector3 left, right;
}
public void Move(Vector2 moveAmount)
{
transform.Translate(moveAmount);
}
}