You probably heard this before cause I read a number of similar Qs, none providing an answer though, but I'm trying to achieve an exact effect of holding and object as in the Amnesia game. xD
I suck at raycasting bad I've read dozens of questions and watched dozens of videos, including the official one but I just don't understand it quite yet. I need a for dummies guide on raycasting. x'D
Anyway here's the code I have now which isn't working. I'm trying to parent it to hold it and unparent to let go, which works only when its not being affected by outside force. And I want it non-kinematic so it doesn't pass through objects but if I make it like that once its pushed out of the raycast I can't seem to unparent it anymore. There's tons of stuff wrong with my code I bet so if anyone has a better way of doing it or a tutorial for exactly that I'll gladly read or watch that, I couldn't find any tutorial for that.
var pickupDistance : int = 10;
var holding : boolean = false;
function Update()
{
//RAYCASTING
var hit : RaycastHit;
var ray : Ray = Camera.main.ScreenPointToRay(Vector3(Screen.width / 2, Screen.height / 2, 0));
if(Physics.Raycast (ray, hit, pickupDistance))
{
//Check if the object is tagged Pickupable and click with mouse
if(Input.GetMouseButtonDown(0) && hit.collider.tag == "Pickupable")
{
Debug.Log("Clicked on " + hit.transform.name);
//Make the tagged object child of the camera and follow it, without being kinematic
hit.transform.parent = gameObject.transform;
hit.rigidbody.useGravity = false;
holding = true;
}
//If mouse button up, make the child object have gravity, unparent and let go
else if(Input.GetMouseButtonUp(0) && holding)
{
hit.rigidbody.useGravity = true;
Drop();
}
//Do the same thing cause the child was affected by outside force and moved from local X 0 and Y 0 coordinates, but in a different way because the child is no longer hit by raycast
else if(hit.transform.localPosition.x > 0 || hit.transform.localPosition.y > 0 && holding)
{
var rigidbodyGravity : Rigidbody;
rigidbodyGravity = gameObject.GetComponentInChildren(Rigidbody);
rigidbodyGravity.useGravity = true;
Drop();
}
}
//if holding is true snap the object to camera local X and Y and the transforms Z
if(holding)
{
hit.transform.localPosition = Vector3(0, 0,hit.transform.position.z);
}
}
//Drop all children
function Drop()
{
transform.DetachChildren();
holding = false;
}
↧