Skip to content

Instantly share code, notes, and snippets.

@sdwrage
Last active May 19, 2017 08:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sdwrage/22a1bc80218db29e74011bd6687cb45d to your computer and use it in GitHub Desktop.
Save sdwrage/22a1bc80218db29e74011bd6687cb45d to your computer and use it in GitHub Desktop.
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