简体   繁体   中英

Always move on surface of the mesh unity C#

I have a cube which i want to move always on the surface of the mesh. Like i have a destination on the surface where player want to go but it should go to the destination without leaving the mesh. Like it go along the surface of the mesh. I know that i Can move towards the destination like this:

   IEnumerator MoveToDirection(Vector3 startPosition, Quaternion orientation, Transform planet)
    {
        GameObject go = GameObject.CreatePrimitive(PrimitiveType.Cube);
        go.transform.rotation = orientation;
        go.transform.position = startPosition;

        while (true)
        {
            go.transform.position=  go.transform.position + go.transform.up * Time.deltaTime* speed;

            yield return new WaitForEndOfFrame();
        }

    }

But don't know how to restrict that it should not leave the surface of the mesh.

There are 3 ways to achieve this effect:

  1. Use physics: attach rigid body/collider to cube/mesh and use something like AddForce
  2. Add every frame move cube to target and calculate position in runtime. If you have formula to calculate height (for example, if you mesh generated from noise or it just sphere) - you can use formula, in other case you can add MeshCollider to mesh and RayCast touch point of mesh/cube every frame + correct cube position
  3. If mesh not endless you can use Unity Nav Mesh system - it will be easiest way to solve complex tasks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM