Hey there helpful Unity people, I’m still quite new to Unity, but I tried making this ‘grab/let go of/throw’ object script.
It should work similar to the half life 2 gravity gun, and i just tag any rigidbodies with ‘pickupableball’.
It works, to a degree: it let’s me pick up things and hold them by holding down ‘grab’ button, then when I let go of ‘grab’, the object drops. And if I’m holding ‘grab’ and press ‘fire1’ - it throws the object forward. Sweet as.
However the object grabbed seems to frequently change shape - i.e I have a beach ball rigidbody that gets squished into an oblong when I grab/throw/re-grab it.
The collider of the rigidbody even changes so it starts rolling around all higgildy piggildy.
var objectPickedUp : boolean = false;
var currentObject : GameObject;
var hit : RaycastHit;
var placement : Transform;
var throwForce : float;
function Update ()
{
if(objectPickedUp == true !Input.GetButton("grab"))
{
dropItLikeItsHot();
}
if(objectPickedUp == true Input.GetButtonDown("Fire1"))
{
getItTheFuckOuttaHere();
}
if(Physics.Raycast (Camera.main.transform.position, Camera.main.transform.TransformDirection (0, 0,1), hit, 2))
{
if(hit.collider.gameObject.tag=="pickupableBall" objectPickedUp == false Input.GetButtonDown("grab"))
{
placement = GameObject.Find("hand").transform;
currentObject = hit.collider.gameObject;
objectPickedUp = true;
pickUpShit();
}
}
}
function pickUpShit()
{
currentObject.rigidbody.isKinematic = true;
currentObject.transform.position = placement.position;
currentObject.transform.parent = placement;
}
function dropItLikeItsHot()
{
objectPickedUp = false;
currentObject.rigidbody.isKinematic = false;
currentObject.transform.parent = null;
currentObject = null;
}
function getItTheFuckOuttaHere()
{
objectPickedUp = false;
currentObject.rigidbody.isKinematic = false;
currentObject.transform.parent = null;
cameraRelativeFront = Camera.main.transform.TransformDirection (0, 0,1);
currentObject.rigidbody.AddForce (cameraRelativeFront * throwForce);
currentObject = null;
}
I’m stumped by this, I’ve somehow turned my player character into some sort of Lennie who crushes everything he touches!
**apologies for my code naming conventions.