Moving an object a fixed amount on its local axis
This does not seem like it should be a super hard thing to do but after 10 straight hours of trying to figure this out, I am still stuck. I am attempting to create a sort of object snap to position feature in my game, where when you point at the side of an object, and click, another object will instantiate there with the same rotation but offset on the transform. I already got the rotation part to work fine, however the movement in the offset is always preformed in world space, meaning that if the object you are snapping to is rotated at all the instantiated object will not be placed right beside it. I have tried using localPosition and it does not seem to help. Here is the code that I have so far...
void snap ()
{
playerRot = hit.transform.root.GetComponent<Transform>().eulerAngles.y;
pos.rotation = Quaternion.AngleAxis(playerRot, Vector3.up);
int sidenum = hit.transform.GetComponent<DB_PlacementArea>().Side;
float offset = hit.transform.GetComponent<DB_PlacementArea>().Offset;
Vector3 tempPos = hit.transform.root.localPosition;
Vector3 tempAdd =
if (sidenum == 1)
{
tempPos.z += offset;
pos.position = tempPos;
}
else if (sidenum == 2)
{
tempPos.x += offset;
pos.position = tempPos;
}
else if (sidenum == 3)
{
tempPos.z -= offset;
pos.position = tempPos;
}
else if (sidenum == 4)
{
tempPos.x -= offset;
pos.position = tempPos;
}
ghost.SetActive(true);
ready = true;
}
Answer by toromano · Nov 09, 2015 at 02:03 PM
If you want to offset position relative to a gameobject, you need to move your relative position from local to world. Let's sat you want to position your gameobject with offset Vector3(1.0f,.0f,.0f)
:
Transform target; // transform matrix of the gameobject that you will position relatively
Vector3 offset = new Vector3(1.0f,.0f,.0f);
transform.position = target.TransformPoint(offset); // this will transform your local position to world position
Hope that helps.
Thanks a lot @toromano You may have just saved me 10 hours of work right there. It works perfectly now !