Onnofon

Rope Mechanic

Oct 10th, 2017
225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.81 KB | None | 0 0
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4.  
  5. public class RopeController : MonoBehaviour
  6. {
  7. public GameObject ropeShooter;
  8.  
  9. private SpringJoint2D rope;
  10. public int maxDurationRope;
  11. private int ropeFrameCount;
  12.  
  13. public LineRenderer lineRenderer;
  14.  
  15.  
  16. void Update()
  17. {
  18. if (Input.GetMouseButtonDown(0))
  19. {
  20. Fire();
  21. }
  22. }
  23.  
  24. void LateUpdate()
  25. {
  26. if(rope != null)
  27. {
  28. lineRenderer.enabled = true;
  29. lineRenderer.SetVertexCount (2);
  30. lineRenderer.SetPosition(0, ropeShooter.transform.position);
  31. lineRenderer.SetPosition(1, rope.connectedAnchor);
  32. }else
  33. {
  34. lineRenderer.enabled = false;
  35. }
  36. }
  37.  
  38. void FixedUpdate()
  39. {
  40. if (rope != null)
  41. {
  42. ropeFrameCount++;
  43.  
  44. if (ropeFrameCount > maxDurationRope)
  45. {
  46. GameObject.DestroyImmediate(rope);
  47. ropeFrameCount = 0;
  48. }
  49. }
  50. }
  51.  
  52. void Fire()
  53. {
  54. Vector3 mousePosition = Camera.main.ScreenToWorldPoint (Input.mousePosition);
  55. Vector3 position = ropeShooter.transform.position;
  56. Vector3 direction = mousePosition - position;
  57.  
  58. RaycastHit2D hit = Physics2D.Raycast (position, direction, Mathf.Infinity);
  59.  
  60. if (hit.collider != null)
  61. {
  62. SpringJoint2D newRope = ropeShooter.AddComponent<SpringJoint2D> ();
  63. newRope.enableCollision = false;
  64. newRope.frequency = 0.2f;
  65. newRope.connectedAnchor = hit.point;
  66. newRope.enabled = true;
  67.  
  68. GameObject.DestroyImmediate(rope);
  69. rope = newRope;
  70. ropeFrameCount = 0;
  71. }
  72. }
  73. }
Advertisement
Add Comment
Please, Sign In to add comment