Hey all, this is my first post so don’t hate on me too hard. Before I put the code down let me briefly describe what I am trying to do.
So I have a top down game where my player moves on the z and x axis (vertical/horizontal). When the mouse moves around the player rotates to face the mouse. So that explains the basic player movement.
What I am trying to do is pick up an object and then have it attach to the player and rotate in coordination with the player (so the player can drop the object wherever they want with ease)
here is what I am doing right now:
The following code will pick up the object and make it the parent:
if (Input.GetMouseButtonDown(1) )
{
// check for collision with interactable object
float radius = 0.50f;
Collider[] objectsInRange = Physics.OverlapSphere(transform.position, radius);
// print all the objects that we are colliding with
for(int q=0;q<objectsInRange.GetLength(0);q++){
// we want to check to see if this is the trash can
if(objectsInRange[q].name == "TrashCan"){
GameObject temp = (GameObject) GameObject.FindWithTag ("Interactable");
isHolding = !isHolding;
if(isHolding){
objHolding = temp;
temp.transform.parent = objPlayer.transform;
Debug.Log(objectsInRange[q].name);
}else{
objHolding.transform.parent = null;
}
}
}
}
When Movement is processed this is what I am doing:
void ProcessMovement()
{
tempVector = rigidbody.GetPointVelocity(transform.position) * Time.deltaTime * 1000;
rigidbody.AddForce (-tempVector.x, -tempVector.y, -tempVector.z);
rigidbody.AddForce (inputMovement.normalized * moveSpeed * Time.deltaTime);
transform.rotation = Quaternion.LookRotation(inputRotation);
transform.eulerAngles = new Vector3(0,transform.eulerAngles.y + 180,0);
transform.position = new Vector3(transform.position.x,0,transform.position.z);
// if we are holding something we want to move it along with our player
if(isHolding){
objHolding.transform.position = new Vector3(transform.position.x,0,transform.position.z);
objHolding.transform.rotation = Quaternion.LookRotation(inputRotation);
objHolding.transform.eulerAngles = new Vector3(0,transform.eulerAngles.y +180,0);
}
}
Right now as you can see the held object is simply attached to the player at the center. I’m trying to figure out how I can have it attach to the front of the player and then rotate with the player around there so the dropping works well. Hopefully I am just missing something in my update. Thanks in advance all.
Edit 5/1
So the issue with attaching not to the center of the player has been dealt with using:
Vector3 tempVector = new Vector3(0,0,1);
object.transform.position + tempVector;
The issue I am having now is that. The object is not rotating “with” the player this means that it is not staying in the same relative position to the player as the player rotates. Does this mean that I have not attached the object correctly?