DELETE
Well I guess there are different approaches for your problem but I’d go like this:
- Add an EmptyObject as child to your FPS-Controller. This represents the position where your weapon will be placed later.
- If your press eg E, make the weapon a child of the FPS-Controller and then position it at the emptyObject you attached before.
Hope that helps you.
If you are a complete noob and need more help than what yodel!dodel offered, this should help.
This is mainly for people that stumble upon this thread through Google.
For the first part of yodel!dodel’s comment he suggests that you should add an empty game object as a child to your First Person Controller. This is pretty much any old game object that doesn’t have any components attached to it. It’s pretty much just a representation for a position. You could just put a position into your code using a Vector3 variable, but this is more visual.
Once you have the empty game object added you need to know how to add children to your game object. To do this you need to go like this:
Weapon.transform.parent = FPController.transform;
Once you do this you need to tell the gun to rotate the right way and be at the right spot. This is where your game object comes in. Make sure you are working in local position to your First Person Controller this will simply make things easier for you, especially for rotation. To do this go like:
Weapon.transform.localPosition = emptyGameObject.transform.localPosition;
Weapon.localEulerAngles = emptyGameObject.localEulerAngles; //This SHOULD work, I usually suck at rotations though, so speak up if it doesn't
And that’s pretty much all you need to know.
Also, tell me if I made any mistakes. I would prefer to not look like a bumbling idiot.
Thank you everyone for your help so far! @xniinja - I did what you suggested, but it seems like I am missing some kind of fundamental concept of unity … It works, but if i walk towards the edge of a level, the cube falls off the map. Likewise, if I walk around it moves with terrain rather than being “pinned” at the empty game object position. Ideas? My code below:
void OnTriggerStay(Collider other) {
if (other.gameObject.name == "First Person Controller" Input.GetKeyDown ("e")) {
gameObject.transform.parent = other.transform;
Transform WeaponMount = other.transform.FindChild ("WeaponMount");
gameObject.transform.localPosition = WeaponMount.localPosition;
gameObject.transform.localEulerAngles = WeaponMount.localEulerAngles;
print ("I want to pick up the weapon.");
}
}
Could you explain what you mean by “moves with terrain.” does that mean it goes up and down when you go over hills? Also, what do you mean by the cube falling off the map. Does that mean the gun or the game object you are attaching to it, or something else?
Oh, make sure you don’t have the rigidbody component on the cube that you are using as the gun. Then it should work like a charm.