- Home /
Question by
egonspengler_84 · May 25, 2021 at 01:30 PM ·
raycastcollision2dboundsmathf.clamp
Trouble with using Mathf.Clamp function in order to create collision detection with raycasts
Hi there,
So I have a scene with a square that I can move left and right with the arrow keys on my keyboard and there are two raycasts that shoot from the bottom right and bottom left corners respectively to detect walls on either side of the square. By using the Mathf.Clamp function I have been able to successfully get the square to collide correctly with the wall on the right side but I can't seem to figure out how to do the same with the wall on the left side.
Here is a video of the issue that you can see here: [MEDIA=youtube]dzcP-huxI54[/MEDIA]
Here is the code that I've written for the square game object:
public class SquareThree : MonoBehaviour
{
private BoxCollider2D _col2D;
public LayerMask _collisionMask;
private Vector2 botRight;
private Vector2 botLeft;
private float rayLength = 1f;
public float moveInput;
public float speed = 0.1f;
// Start is called before the first frame update
void Start()
{
_col2D = GetComponent<BoxCollider2D>();
}
// Update is called once per frame
void FixedUpdate()
{
moveInput = Input.GetAxisRaw("Horizontal");
Bounds bounds = _col2D.bounds;
botRight = new Vector2(bounds.max.x,bounds.min.y);
botLeft = new Vector2(bounds.min.x,bounds.min.y);
RaycastHit2D hitR = Physics2D.Raycast(botRight,Vector2.right,rayLength,_collisionMask);
Debug.DrawRay(botRight,Vector2.right * rayLength, Color.red);
RaycastHit2D hitL = Physics2D.Raycast(botLeft,Vector2.left,rayLength,_collisionMask);
Debug.DrawRay(botLeft,Vector2.left * rayLength, Color.red);
if(hitR){
transform.Translate( Mathf.Clamp(hitR.distance,0,moveInput * speed),0,0);
}else if(hitL){
transform.Translate( Mathf.Clamp(-hitR.distance,moveInput * speed,0),0,0);
}else{
transform.Translate(moveInput * speed,0,0);
}
}//end of fixed update
}
If anyone has any suggestions as to what I'm doing wrong I would appreciate it very much. Thanks
Comment