I have 2 game objects - the player, a moving platform. The platform has 2 box colliders; one a trigger, the other not. The player has a capsule collider and a character controller. When the player lands on top of the platform, it enters the trigger and makes the platform its parent so that the platform can move the player with it. This works perfectly until the platform moves downward on the Y axis. What I believe is occurring is the following:
- Platform moves down
- Trigger Exit activated
- Platform removed as player parent
- Gravity applies to player
- Player enters trigger
- Repeat
This causes the player object to constantly bounce the entire way down. Is there a way to make the child (player) move with its parent (platform) within the same frame, or before trigger events occur?
My code for reference:
/////////////////////////////
//within player object
/////////////////////////////
void OnTriggerStay(Collider other)
{
if(other.gameObject.tag == "Platform")
{
transform.parent = other.gameObject.transform;
}
}
private void OnTriggerExit(Collider other)
{
if(other.gameObject.tag == "Platform")
{
transform.parent = null;
}
}
////////////////////////
// Within platform
////////////////////////
void Update () {
if (!isResting)
{
if (xAxis)
{
transform.position += new Vector3((speed * (xInvert ? -1 : 1)) * Time.deltaTime, 0, 0);
}
if (yAxis)
{
transform.position += new Vector3(0, (speed * (yInvert ? -1 : 1)) * Time.deltaTime, 0);
}
if (zAxis)
{
transform.position += new Vector3(0, 0, (speed * (zInvert ? -1 : 1)) * Time.deltaTime);
}
}
elapsedTime += Time.deltaTime;
if(elapsedTime >= travelTime && !isResting)
{
elapsedTime = 0f;
xInvert = !xInvert;
yInvert = !yInvert;
zInvert = !zInvert;
if(restTime > 0f)
{
isResting = true;
}
}
if(isResting)
{
if(elapsedTime >= restTime)
{
elapsedTime = 0f;
isResting = false;
}
}
}