- Home /
picking object
I want to pick up object in my game. I found this script and I changed the tag to"Pick", but my object dont follow the mouse and this script dont work. What should i do?
var grabRange: float = 2;
var pickPos: Vector3 = Vector3 (0, 0.5, 1.1);
var force: float = 30;
private var pickObj: Transform = null;
private var rBody: Rigidbody;
private var hadRBody: boolean;
private var freezeRot: boolean;
function Update(){
if (Input.GetMouseButtonDown(0)){ // if left button pressed...
var hit: RaycastHit;
var ray = Camera.main.ScreenPointToRay(Input.mousePosition); // create a ray from the mouse pointer
// if object "Pick" clicked, and inside grabRange...
if (Physics.Raycast(ray, hit) && hit.transform.tag == "Pick" && hit.distance < grabRange){
pickObj = hit.transform; // save the object's transform...
pickObj.parent = transform; // child it to the player...
rBody = pickObj.rigidbody; // and get its rigidbody, if any
if (rBody){ // if already had a rigidbody...
freezeRot = rBody.freezeRotation; // save its freezeRotation property
hadRBody = true;
} else { // if no rigidbody, add one:
rBody = pickObj.gameObject.AddComponent(Rigidbody);
hadRBody = false;
}
rBody.freezeRotation =true; // disable physical rotations
}
}
if (Input.GetMouseButtonUp(0) && pickObj){
if (hadRBody){ // if already had a rigidbody...
rBody.freezeRotation = freezeRot; // restore freezeRotation
} else { // if not, destroy the added rigidbody:
Destroy(rBody);
}
pickObj.parent = null; // unchild the object...
pickObj = null; // and signal that's nothing is picked anymore
}
}
function FixedUpdate(){
if (pickObj){
var error = transform.TransformPoint(pickPos) - pickObj.position;
rBody.velocity = force * error;
}
}
Comment
Answer by Berenger · Nov 19, 2012 at 12:59 PM
First, try to understand the script. Then, add print() here and there to see what's going on, which value is correct and which isn't.
Your answer
Follow this Question
Related Questions
pick up a gun problem 1 Answer
Pick the oldest object from an array. 2 Answers
Storing items in inventory 1 Answer
In what way can I make a GUI Inventory? 0 Answers
FPS Equiping items? 0 Answers