- Home /
[C#] More elegant solution to making player move with moving platform?
Using Unity version 4.2.1f
My latest project is a 3D puzzle game which makes use of many moving components. When activated they would rotate or move from point to point. Because of this I needed a way for the player to stay "attached" to them to prevent the platforms from sliding out from under them since some of them move very quickly.
Originally I intended to use OnTriggerEnter and OnTriggerExit events to mess with parenting of the game object. I quickly discovered that when the object is parented OnTriggerExit is no longer fired, a change that the ask section tells me was changed in 3.2. I don't particularly understand how that works but working around it was fairly easy. The only problem is that it feels a little cheap (for lack of a better word). I'll of course implement tag checks to prevent it parenting any other objects that pass through it.
Is there any more elegant solution, or one that would be considered "better" for handling this?
void OnTriggerStay(Collider col)
{
if(col.CompareTag("Player"))
{
if(TP_Controller.CharacterController.isGrounded)
{
//Parent object rather than the empty object containing the trigger.
col.transform.parent = this.transform.parent;
}
else
{
col.transform.parent = null;
}
}
}
Answer by HarshadK · Apr 04, 2014 at 11:41 AM
You can think of using Fixed Joint if you are using rigidbodies.
Unity Reference Manual states that:
Fixed Joints restricts an object's movement to be dependent upon another object. This is somewhat similar to Parenting but is implemented through physics rather than Transform hierarchy. The best scenarios for using them are when you have objects that you want to easily break apart from each other, or connect two object's movement without parenting.
But one issue with using this is that it restricts the movement of objects. If that is not an issue with you and you are using rigidbodies then Fixed Joint is the way to go.
Unfortunately I wanted the player to be able to move independently of the platform but to be "dragged" along with it, so that the player can walk off the platform or jump off at any point. Thanks for the useful information though, that's bound to come in handy further down the project.