0
\$\begingroup\$

So I'm trying to make a collision detection system for a kinematic rigidbody for a gameobject but for some reason the results in which the gameobject stop is always different. I tried missing around with the distance of the raycast but still the problem persist any help would be appreciated.

private float deltaX, deltaY;
private float rayDistance;

private Rigidbody2D _rb;

private bool moveAllowed = false;
private bool grounded = false;


// Use this for initialization
void Start ()
{
    _rb = GetComponent<Rigidbody2D>();
    rayDistance = GetComponent<BoxCollider2D>().bounds.extents.y;
}

// Update is called once per frame
void Update ()
{

    Debug.DrawRay(transform.position, -Vector2.up * (rayDistance + 0.1f), Color.green);

    Vector2 touchPosition = Camera.main.ScreenToWorldPoint(Input.mousePosition);

    if (Input.GetMouseButtonDown(0))
    {
        // Check if the mouse is touching the gameobject
        if (GetComponent<BoxCollider2D>() == Physics2D.OverlapPoint(touchPosition))
        {
            _rb.bodyType = RigidbodyType2D.Dynamic;
            _rb.freezeRotation = true;
            // Get the offsets between the touch position and the center of the gameobject
            deltaX = touchPosition.x - transform.position.x;
            deltaY = touchPosition.y - transform.position.y;

            moveAllowed = true;
        }
    }


    if (Input.GetMouseButton(0) && moveAllowed)
    {

        _rb.velocity = new Vector2((touchPosition.x - transform.position.x) - deltaX,
            (touchPosition.y - transform.position.y) - deltaY) * 10;
    }

    if (Input.GetMouseButtonUp(0))
    {

        int roundedX = Mathf.RoundToInt(transform.position.x);
        transform.position = new Vector2(roundedX, transform.position.y);
        _rb.velocity = Vector2.down * 10;
        moveAllowed = false;
        _rb.bodyType = RigidbodyType2D.Kinematic;
    }

    if (grounded && !moveAllowed)
    {
        _rb.velocity = Vector2.zero;
    }

}

private void FixedUpdate()
{
    int layerMask = 1 << 8;
    layerMask = ~layerMask;

    RaycastHit2D hit = Physics2D.Raycast(transform.position, -Vector2.up, rayDistance + 0.1f, layerMask);

    if (hit.collider != null)
    {
        grounded = true;
        //Debug.Log("hit: " + hit.transform.name);
    }
    else
    {
        grounded = false;
    }
}
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.