- Home /
Having a child gameobject reside within restricted cooridinates?
I have a child gameobject that I want to smoothly move to and fro, such that it will attempt to stay within predefined coordinates.
if(child != null)
{
float curX = child.transform.localPosition.x;
float curY = child.transform.localPosition.y;
float curZ = child.transform.localPosition.z;
float tempX = 0.0f;
float tempY = 0.0f;
float tempZ = 0.0f;
xVelocity = child.transform.InverseTransformDirection(child.rigidbody.velocity).x;
yVelocity = child.transform.InverseTransformDirection(child.rigidbody.velocity).y;
zVelocity = child.transform.InverseTransformDirection(child.rigidbody.velocity).z;
if(curZ > 1.6f)
{
tempZ = -(Mathf.SmoothDamp(curZ, 1.5f, ref zVelocity, 0.01f)*2);
}
else if(curZ < 1.4f && curZ > 0.3f)
{
tempZ = (Mathf.SmoothDamp(curZ, 1.5f, ref zVelocity, 0.01f)*2);
}
else
{
tempZ = 0;
}
if(curX > 0.1f)
{
tempX = -(Mathf.SmoothDamp(curX, 0.0f, ref xVelocity, 0.1f)*2);
}
else if(curX < -0.1f)
{
tempX = -(Mathf.SmoothDamp(curX, 0.0f, ref xVelocity, 0.1f)*2);
}
else
{
tempX = 0;
}
if(curY > 4.1f)
{
tempY = (Mathf.SmoothDamp(curY, 4.0f, ref yVelocity, 0.2f)*2);
}
else if(curY < 3.9f)
{
tempY = -(Mathf.SmoothDamp(curY, 4.0f, ref yVelocity, 0.2f)*2);
}
else
{
tempY = 0;
}
Vector3 tempVec = new Vector3(tempX,tempY,tempZ);
child.transform.TransformDirection(tempVec);
child.rigidbody.velocity = tempVec;
}
However, using the code above, the child gameobject does not stay in the correct location. I am converting the velocity to local, and then back to world (which should make it function correctly, I think).
Am I overlooking something? When you face due north, the code executes properly, however, if you rotate, the child will function strangely. and if you are facing due south, the code will operate the opposite, with the exemption of the following code:
else if(curZ < 1.4f && curZ > 0.3f)
{
tempZ = (Mathf.SmoothDamp(curZ, 1.5f, ref zVelocity, 0.01f)*2);
}
What am I doing incorrectly?
your not taking into account its rotation relative to the parent.
The moment you rotate the parent its north isn't the childs north.
You can't use the parents positional information without using its rotational information probably.
$$anonymous$$aybe you should just child a collider that bounds the limit and when you hit the collider you impart force that sends you in the opposite direction of your current heading?