Last active
May 19, 2017 08:06
-
-
Save sdwrage/22a1bc80218db29e74011bd6687cb45d to your computer and use it in GitHub Desktop.
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
using System.Collections; | |
using System.Collections.Generic; | |
using UnityEngine; | |
public class GrabObject : MonoBehaviour { | |
protected GameObject heldObject; | |
protected RaycastHit hit; | |
public float heldForwardPosition = 1f; | |
public GameObject HeldObject | |
{ | |
get { return this.heldObject; } | |
set { this.heldObject = value; } | |
} | |
// Use this for initialization | |
void Start () { | |
} | |
// Update is called once per frame | |
void FixedUpdate () { | |
GameObject detectedGrabbable = CheckForGrabbables (); | |
if (detectedGrabbable != null) { | |
HeldObject = detectedGrabbable; | |
HeldObject.GetComponent<Rigidbody> ().useGravity = false; | |
} | |
holdHeldObject (); | |
if (HeldObject && Input.GetKeyDown (KeyCode.R)) { | |
GameObject thrownObject = HeldObject; | |
HeldObject = null; | |
thrownObject.GetComponent<Rigidbody>().AddForce(500f * Vector3.forward); | |
} | |
} | |
GameObject CheckForGrabbables () { | |
Ray MyRay = new Ray (Camera.main.transform.position, Camera.main.transform.forward); | |
Physics.Raycast(MyRay, out hit, 50f); | |
if (hit.collider != null && hit.collider.gameObject.tag == "Grabbable") { | |
return hit.collider.gameObject; | |
} | |
return null; | |
} | |
void holdHeldObject() { | |
if (HeldObject) { | |
HeldObject.GetComponent<Rigidbody>().velocity = (Camera.main.transform.TransformPoint(Vector3.forward * heldForwardPosition) - HeldObject.GetComponent<Rigidbody>().position) / Time.fixedDeltaTime; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment