I have a sword in my game that I am attaching to my character based on tags.
var target : Transform;
function Start ()
{
target = GameObject.FindWithTag("RHand").transform;
transform.parent = target.transform;
transform.localPosition = Vector3(0, 0, 0);
}
My sword is the parent object, there are 2 children, blade and hilt. I’ve attached this code to the hilt so that the character is holding onto the sword by the right place. How can I get the blade to orient itself to the right location based on where the hilt is? I’ll eventually change this from a Start function to an Update function so when I walk around the sword stays in my hand, currently just need some way to get it all attached.
Thanks!
It seems you don’t understand how parent-child relationship works. A child only have one parent. If the hilt is a child of your sword and you set the parent of the hilt to something else, it’s no longer a child of the sword. It’s not related anymore to the sword. If you want the hilt-position to be the attachpoint of the sword make it the parent of your sword. You can do this:
function Start ()
{
var target = GameObject.FindWithTag("RHand").transform;
var sword = transform.parent;
transform.parent = target.transform;
sword.parent = transform;
transform.localPosition = Vector3.zero;
transform.localRotation = Quaternion.identity;
}
-RHand
-Sword
-blade
-hilt
After the start function:
-RHand
-hilt
-Sword
-blade
You want to offset the sword’s new local position by the hilt’s offset relative to the sword. So what you want is the negative offset of the hilt. After the sword (not the hilt) is parented to the hand, set the sword’s local position to be the opposite of the hilt’s local position. So:
transform.localPosition = -Vector3.Scale (hilt.localPosition, transform.localScale;
This code would go on the sword (not the hilt, as you have it now) and you have to scale it by the sword’s scaling just in case it’s not (1,1,1).