Question about creating a specific first person player prefab
Hi, I am trying to create a first person player prefab that won't affect the physical movement of in-game objects while colliding with them.
for instance, when the player jumps on a moving cube that is not affected by gravity, the cube keeps moving along without any physical affect from the player. and the player is able to stand on it while it is moving and not affect its movement.
Can anybody give me a tip on what are the possible ways to achieve that?
Really appreciated!
Answer by MrMeows · Oct 22, 2015 at 08:15 AM
In my experience, the only way to stand on a moving object is to make the player a child of the moving object. Add this to the moving object:
void OnCollisionEnter(Collision someCollision)
{
if(someCollision.collider.isPlayer) //Replace isPlayer with your own method
{
someCollision.collider.transform.parent = transform;
}
}
void OnCollisionExit(Collision someCollision)
{
if(someCollision.collider.isPlayer)
{
someCollision.collider.transform.parent = null;
}
}
Answer by Statement · Oct 22, 2015 at 12:59 PM
You could do this using layers and kinematic rigidbodies that follow regular rigidbodies.
Kinematic rigidbodies don't react to collisions, and you must move them through scripts.
Regular rigidbodies react to collisions, and movement is automatic.
If you have a bunch of cubes that can collide with each other, but don't want to get affected by the player, but the player affected by the cubes, you could possibly do something like this:
For each cube, you actually have two cubes.
One that has a collider and a kinematic rigidbody. Set layer to "KinematicLayer".
One that has a collider and a regular rigidbody. Set layer to "RegularLayer".
In FixedUpdate, the regular rigidbody copies position to the kinematic rigidbody.
(The KinematicLayer, RegularLayer and PlayerLayer does not exist by deafult, you have to create them yourself)
In the physics collision matrix, make it so that
KinematicLayer does not collide with KinematicLayer
KinematicLayer does not collide with RegularLayer
RegularLayer does not collide with KinematicLayer
RegularLayer does collide with RegularLayer
PlayerLayer does collide with KinematicLayer
PlayerLayer does not collide with RegularLayer
Now, your player should be able to walk on the kinematic rigidbodies. The kinematic rigidbodies position is determined by their regular rigidbody. The regular rigidbody acts like usual.
Note that this can cause the player to get squished under the kinematic rigidbodies since the player can't affect them at all.