Skip to content

Instantly share code, notes, and snippets.

@DonHaul
Created February 7, 2017 23:48
Show Gist options
  • Save DonHaul/fd5bf4967a95cd4a892b8ff2f9262d91 to your computer and use it in GitHub Desktop.
Save DonHaul/fd5bf4967a95cd4a892b8ff2f9262d91 to your computer and use it in GitHub Desktop.
using UnityEngine;
//makes sure object has this componentes
[RequireComponent(typeof(Rigidbody2D),typeof(SpringJoint2D),typeof(LineRenderer))]
public class grapplinghook : MonoBehaviour {
SpringJoint2D joint;
LineRenderer lr;
[SerializeField]
float step = .1f;
//tells whether or not rope is active
bool state=false;
Vector3 anchorPos;
void Start () {
//Sets Conponents and their parameters
lr = GetComponent<LineRenderer> ();
lr.numPositions=2;
lr.startWidth = .1f;
lr.endWidth = .1f;
joint = GetComponent<SpringJoint2D> ();
joint.frequency = 1000000;
}
// Update is called once per frame
void Update () {
//Create Rope
if (Input.GetMouseButtonDown (0)) {
Grapple (true);
}
else if (Input.GetMouseButtonUp(0))
{
//Delete Rope
Grapple(false);
}
//If E is pressed rope shrinks
if (Input.GetKey (KeyCode.E)) {
joint.distance -= step;
}
else if (Input.GetKeyUp (KeyCode.E)) {
//delete rope
Grapple (false);
}
//if rope is active, it updates rope position
if (state) {
lr.SetPosition (0, transform.position);
lr.SetPosition (1, anchorPos);
}
}
void Grapple(bool state)
{
//enables/disables components
joint.enabled = state;
lr.enabled = state;
//if rope is active sets its anchor point
if (state==true) {
anchorPos = Input.mousePosition;
anchorPos.z = 10;
anchorPos = Camera.main.ScreenToWorldPoint (anchorPos);
joint.connectedAnchor = anchorPos;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment