32bit_jam_conjure/Assets/GrappleHook.cs
2022-10-18 23:22:05 -04:00

95 lines
2.8 KiB
C#

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GrappleHook : MonoBehaviour
{
[SerializeField]
private float maxGrappleDist = 200;
[SerializeField]
private LayerMask grappleableLayer; // TODO create layermask
[SerializeField]
private Vector3 gunPos = new Vector3 (-0.5f, 0f, 0f);
private SpringJoint joint;
private LineRenderer lr;
RaycastHit hit;
private bool grappled = false;
[SerializeField]
private Transform hitMarker; //TODO obj this should be a sprite or something idk
// Start is called before the first frame update
void Start()
{
lr = gameObject.GetComponentInChildren<LineRenderer>();
lr.enabled = false;
hitMarker.gameObject.SetActive(false);
}
// Update is called once per frame
void Update()
{
if(Input.GetMouseButtonUp(0)){//TODO Change to correct input system
EndGrapple();
}
if(grappled){
DrawRope();
if(Input.GetMouseButtonDown(1)){
joint.minDistance = 0f;
joint.maxDistance = 0f;
}
return;
}
Aim();
}
private void Aim(){
Vector3 mousePos;
mousePos = Input.mousePosition;
mousePos.z = Mathf.Abs(Camera.main.transform.position.z);
mousePos = Camera.main.ScreenToWorldPoint(mousePos);
Vector3 aimDir = (mousePos - gameObject.transform.position).normalized;
if(!hitMarker.gameObject.activeSelf)hitMarker.gameObject.SetActive(true);
hitMarker.position = gameObject.transform.position + aimDir * maxGrappleDist;
if(Physics.Raycast(gameObject.transform.position, aimDir, out hit, maxGrappleDist, grappleableLayer)){
hitMarker.position = hit.point;
if(Input.GetMouseButtonDown(0)){
StartGrapple(hit);
}
}
}
private void DrawRope(){
if(!grappled)return;
// TODO Draw gradually towards point
lr.SetPosition(0, gameObject.transform.position);
lr.SetPosition(1, hit.point);
if(!lr.enabled)lr.enabled = true;
}
private void StartGrapple(RaycastHit hit){
grappled = true;
//Display
hitMarker.gameObject.SetActive(false);
joint = gameObject.AddComponent<SpringJoint>();
joint.anchor = gunPos;
joint.autoConfigureConnectedAnchor = false;
joint.maxDistance = hit.distance * 0.8f;
joint.minDistance = hit.distance * 0.25f;
joint.connectedAnchor = hit.point;
joint.spring = 4.5f * 5f;
joint.damper = 7f;
joint.massScale = 4.5f;
}
private void EndGrapple(){
grappled = false;
lr.enabled = false;
Destroy(joint);
}
}