# 2D GRAPPLE GUN QUEST: ‘Spiderman’ - Solutions

Quest: 2D Grapple Gun Quest
Challenge: Spiderman

Feel free to share your solutions, ideas and creations below. If you get stuck, you can find some ideas here for completing this challenge.

After many hours of head scratching and getting more comforatable with lerps, I’m super happy that I figured out a solution to the spiderman challenge. It’s not perfect, but it works lol woop woop!

``````

using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GrapplingHook : MonoBehaviour
{
[SerializeField] private float distance = 10f;
[SerializeField] private LineRenderer line;
[SerializeField] private GameObject playerHand;
[SerializeField] private GameObject lerpDot;
[SerializeField] private float lerpSpeed = 1f;
[SerializeField] private float pullDelay = 1f;

DistanceJoint2D joint;
Vector3 targetPos;
RaycastHit2D hit;

float t = 0f;
bool isDrawing = false;

private void Start()
{
joint = GetComponent<DistanceJoint2D>();
joint.enabled = false;
line.enabled = false;

lerpDot.transform.position = playerHand.transform.position;
}

private void Update()
{
PullPlayer();
DrawLine();

if (Input.GetMouseButtonDown(0))
{
targetPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
targetPos.z = 0;

hit = Physics2D.Raycast(playerHand.transform.position, targetPos - playerHand.transform.position, distance, mask);

if (hit.collider != null && hit.collider.gameObject.GetComponent<Rigidbody2D>() != null)
{
joint.enabled = true;
joint.connectedBody = hit.rigidbody;
joint.connectedAnchor = hit.transform.InverseTransformPoint(hit.point);
joint.distance = Vector2.Distance(playerHand.transform.position, hit.point);

line.enabled = true;
isDrawing = true;
}
}

if (Input.GetMouseButton(0))
{
line.SetPosition(0, playerHand.transform.position);
}

if (Input.GetMouseButtonUp(0))
{
joint.enabled = false;
line.enabled = false;
isDrawing = false;
t = 0f;
}
}

private void DrawLine()
{
if(isDrawing)
{
t += Time.deltaTime * lerpSpeed;

lerpDot.transform.position = Vector3.Lerp(playerHand.transform.position, hit.point, t);

line.SetPosition(0, playerHand.transform.position);
line.SetPosition(1, lerpDot.transform.position);
}

}

private void PullPlayer()
{
//Challenge 2:
if (t > pullDelay)
{
joint.distance -= 0.1f;
}
if (joint.distance < 0.1f && joint.enabled && line.enabled)
{
//joint.enabled = false;
line.enabled = false;
}
}
}

``````
1 Like