Created
July 1, 2020 15:09
-
-
Save saturngamesss/e79f9e0ed07fc22fc82c132f1143a3e0 to your computer and use it in GitHub Desktop.
Grappling gun with raycasthit2D code for Unity.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//************** REAL GAMES STUDIO *************** | |
//************************************************ | |
//realgamesss.weebly.com | |
//gamejolt.com/@Real_Game | |
//realgamesss.newgrounds.com/ | |
//real-games.itch.io/ | |
//youtube.com/channel/UC_Adg-mo-IPg6uLacuQCZCQ | |
//************************************************ | |
using UnityEngine; | |
public class GrapplingGunRaycasthit2D : MonoBehaviour | |
{ | |
public LayerMask ropeLayerMask; | |
public float distance = 90.0f; | |
LineRenderer line; | |
DistanceJoint2D rope; | |
Vector2 lookDirection; | |
bool checker = true; | |
void Start() | |
{ | |
rope = gameObject.AddComponent<DistanceJoint2D>(); | |
line = GetComponent<LineRenderer>(); | |
rope.enabled = false; | |
line.enabled = false; | |
} | |
void Update() | |
{ | |
line.SetPosition(0, transform.position); | |
lookDirection = Camera.main.ScreenToWorldPoint(Input.mousePosition) - transform.position; | |
Debug.DrawLine(transform.position, lookDirection); | |
if (Input.GetMouseButtonDown(0) && checker == true) | |
{ | |
RaycastHit2D hit = Physics2D.Raycast(transform.position, lookDirection, distance, ropeLayerMask); | |
if (hit.collider != null) | |
{ | |
checker = false; | |
SetRope(hit); | |
} | |
} | |
else if (Input.GetMouseButtonDown(0) && checker == false) | |
{ | |
checker = true; | |
DestroyRope(); | |
} | |
} | |
void SetRope(RaycastHit2D hit) | |
{ | |
rope.enabled = true; | |
rope.connectedAnchor = hit.point; | |
line.enabled = true; | |
line.SetPosition(1, hit.point); | |
} | |
void DestroyRope() | |
{ | |
rope.enabled = false; | |
line.enabled = false; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment