So my code is supposed to pick up (add child to player controller) a nearby animal when the H key is pressed. Unfortunately, if the player is behind the animal he’s trying to pick up, the animal is placed behind the player and out of sight. Any advice for fixing this?
void Update () {
GameObject[] agent;
if(Input.GetKeyDown(KeyCode.H)){//if h was pressed
agent = GameObject.FindGameObjectsWithTag("Finish");
foreach(GameObject ag in agent){//find all animals with the tag of finish
if(holding == false){//only pick up one
if((ag.rigidbody.position-rigidbody.position).magnitude<15){//find closest animal to player and pick it up
Held = ag;
if(Held.transform.position.z > transform.position.z){
Held.transform.parent = transform;
}else{
Debug.Log("TEST");
Held.transform.parent = transform;
}
holding = true;
}
}
}
}
if(holding == true){//if one is being held, reset position
if(hold2 == false){
hold2 = true;
Held.transform.position = new Vector3(-10f,0,0);
}
Held.transform.localPosition = Vector3.zero;
}
if(Input.GetKeyUp(KeyCode.H) && holding == true){//if something is being held, upon release detach the player from the animal
holding = false;
Held.transform.parent = null;
Held.rigidbody.velocity = Vector3.zero;
}
}