i have a box that can be grabbed by player and move it around, I have code that handle resistance to box so it wont get pushed or go through walls. now it works as far as I seen, but seems like its not enough, player can still get box through wall if he pushes to hard, how to make it more resistable?
private readonly float grabDistance = 1f;
private GameObject grabbedObject;
private Rigidbody2D grabbedRigidbody;
public void TryGrab()
{
int boxLayerMask = LayerMask.GetMask("Box");
int pressurePadLayerMask = LayerMask.GetMask("PressurePad");
Vector2 raycastOrigin = (Vector2)transform.position + facingDirection * 0.3f;
RaycastHit2D hit = Physics2D.Raycast(raycastOrigin, facingDirection, grabDistance, boxLayerMask & ~pressurePadLayerMask);
if (hit.collider != null && hit.collider.CompareTag("Box"))
{
grabbedObject = hit.collider.gameObject;
grabbedObject.transform.parent = transform;
grabbedRigidbody = grabbedObject.GetComponent<Rigidbody2D>();
}
}
void OnCollisionStay2D(Collision2D collision)
{
if (grabbedObject != null && collision.gameObject.CompareTag("Wall"))
{
Vector2 directionToWall = (collision.transform.position - grabbedObject.transform.position).normalized;
Vector2 oppositeDirection = -Vector2.Dot(grabbedRigidbody.velocity, directionToWall) * directionToWall;
grabbedRigidbody.velocity += oppositeDirection * 8f;
}
}
this is my code in the player script to handle the logic.
box does not have any script
any suggestion or solutions that can be used in inspector is also a good choice to try if you have any, I have tried a few options but nothing seems to work so far. box is also child of player when grabbed