Reputation: 143
I am currently working on procedurally generating celestial bodies. Plan is to cover as many as possible, but at the moment I have only got the configuration ready for stars, planets, moons and asteroids.
Anyway, back on the primary point. I want to be able to walk around on the randomly generated planets and for that, I need to assign a mesh collider to the Sphere mesh I am using for the terrain generation.
I made sure to add the MeshCollider component after I have assigned the mesh to the meshfilter, just in case. And after all the noise layers are done with the "sculpting" of the vertices of that mesh, I set the collider mesh to the meshfilter mesh.
terrainMeshFilter.sharedMesh = shapeSettings.CreateTerrain(origin);
if(terrainSphere.GetComponent<MeshCollider>() == null) terrainSphere.AddComponent<MeshCollider>();
terrainSphere.GetComponent<MeshCollider>().sharedMesh = null;
terrainSphere.GetComponent<MeshCollider>().sharedMesh = terrainMeshFilter.sharedMesh;
I tested this, and it didn't produce the expected results. The player is, for some reason, floating. I have made sure to apply a "gravity" force, pulling the player towards the planet like so:
Rigidbody rb = player.GetComponent<Rigidbody>();
Transform playerTransform = player.GetComponent<Transform>();
Vector3 gravityDirection = (playerTransform.position - origin).normalized;
if(rb != null){
rb.useGravity = false;
rb.isKinematic = true;
rb.AddForce(gravityDirection * gravity);
}
But the player is stuck "midair". It won't stick to the ground. And another weird thing that is happening is that, if I "run" around the planet with the player midair, and hit some mountain sticking up very highly, then the collision with the mountain is registered correctly. That would suggest that the MeshCollider is assigned correctly, but if that is the case, why is the player floating midair?
Any help is appreciated. Thank you in advance.
Note: I have also assigned some images below picturing the problem from the player's perspective on the planet, and from a third person perspective outside the planet (the capsule is the player).
Upvotes: 0
Views: 465
Reputation: 756
Without seeing the mesh wireframe is impossible to give you a proper answer, but judging from the little code you have shared I'd say that your mesh doesn't coincide with your actual mesh data. This can easily be because you are using sharedMesh instead of mesh: especially on a procedurally generated object those data might not match at all, and writing them can cause undesired effects.
Also, about gravity, your approach is too simplistic. Have a look at this video about faux gravity systems and attractors for walking on planets.
~Pino
Upvotes: 1