Problem with raycasting towards mouse
I made a grappling hook that shoots out a ray and attaches to a rigidbody. The problem is the ray is always shot upwards, instead of towards the mouse.
public bool grapple = false;
DistanceJoint2D joint;
Vector3 targetPos;
RaycastHit2D hit;
public float distance = 10f;
public LayerMask mask;
void Start()
{
joint = GetComponent<DistanceJoint2D>();
joint.enabled = false;
}
void Update()
{
if (Input.GetButtonDown("Grapple") && grapple == true)
{
targetPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
hit = Physics2D.Raycast(transform.position, targetPos - transform.position, distance, mask);
Debug.DrawRay(transform.position, targetPos - transform.position);
if (hit.collider != null && hit.collider.gameObject.GetComponent<Rigidbody2D>())
{
joint.enabled = true;
Vector2 connectPoint = hit.point - new Vector2(hit.collider.transform.position.x, hit.collider.transform.position.y);
connectPoint.x = connectPoint.x / hit.collider.transform.localScale.x;
connectPoint.y = connectPoint.y / hit.collider.transform.localScale.y;
joint.connectedAnchor = connectPoint;
joint.connectedBody = hit.collider.gameObject.GetComponent<Rigidbody2D>();
joint.distance = Vector2.Distance(transform.position, hit.point);
}
}
if (Input.GetButtonUp("Grapple"))
{
joint.enabled = false;
}
}
Comment