You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

85 lines
2.0 KiB

  1. using UnityEngine;
  2. using System.Collections;
  3. using UnityEngine.UI;
  4. public class magnetGun2 : MonoBehaviour {
  5. public Camera camera;
  6. public GameObject crossHair;
  7. public GameObject gravityWell;
  8. public thirdPersonController playerController;
  9. public float magnetMaxRange;
  10. public float magnetMinRange;
  11. private Collider gravityTarget;
  12. // Use this for initialization
  13. void Start () {
  14. magnetMinRange += playerController.cameraDistance;
  15. magnetMaxRange += playerController.cameraDistance;
  16. }
  17. // Update is called once per frame
  18. void Update () {
  19. RaycastHit target = testItem ();
  20. if (gravityTarget != null)
  21. pickUpItem (target);
  22. }
  23. //test to see if player can move item
  24. private RaycastHit testItem(){
  25. RaycastHit hit;
  26. //resets cross hair to white
  27. crossHair.GetComponent<RawImage> ().color = Color.white;
  28. //cast ray from camera through the crosshair on screen
  29. Ray ray = camera.ScreenPointToRay (crossHair.transform.position);
  30. Debug.DrawRay (ray.origin, ray.direction*magnetMaxRange, Color.green);
  31. // if player can pickup object turn crosshair red
  32. // if object is close enougth to move with it turn blue;
  33. if (Physics.Raycast (ray, out hit, magnetMaxRange)) {
  34. if (hit.collider.tag == "moveable"){
  35. gravityTarget = hit.collider;
  36. Debug.DrawRay (ray.origin,ray.direction*magnetMaxRange, Color.red);
  37. crossHair.GetComponent<RawImage>().color = Color.red;
  38. if (Vector3.Distance (hit.point, camera.transform.position) <= magnetMinRange) {
  39. crossHair.GetComponent<RawImage>().color = Color.blue;
  40. }//end blue
  41. }//end red
  42. }//end raycast
  43. return hit;
  44. }// end testItem()
  45. private void pickUpItem(RaycastHit hit){
  46. Collider item = hit.collider;
  47. //prepares item to be lifted
  48. item.attachedRigidbody.useGravity = false;
  49. item.attachedRigidbody.drag = 3.0f;
  50. item.attachedRigidbody.constraints = RigidbodyConstraints.FreezeRotation;
  51. gravityWell.transform.position = item.transform.position;
  52. transform.LookAt (gravityWell.transform.position, Vector3.up);
  53. }
  54. }