简体   繁体   中英

How to perfectly place a gameObject on a mesh through C# script in unity?

Summary: I have a gameobject that have a rock mesh. However, the bottom of the mesh is hallow and ugly. I want to place it on a mesh that looks like a hill, so that the player cannot see the gameobject's ugly and hallow bottom.

I have a script that uses raycast to place the rock. The raycast is above the mesh. When I raycast downwards, I get a Vector3 on the hill looking mesh. I place that rock on that point, and I can see its bottom! How to avoid that using C# code?

Here is my full question:

How To: Rotate and move a GameObject, which have a "mesh" as its component, so that it sits on another mesh "perfectly" without seeing the GameObject's bottom through c# script in Unity.

How it looks like now

What I want to achieve

Any kinds of help is appreciated!!

Here's a snippet of code which uses the raycast hit's normal value to rotate the rock mesh.

The normal is a vector heading outwards (perpendicular) of the mesh geometry between vertices:

https://en.wikipedia.org/wiki/Vertex_normal#/media/File:Vertex_normals.png

If you place this script on the rock mesh, it will tell the rock mesh that its upward vector is the same as the normal where the raycast point is.

using UnityEngine;

public class StickToTerrain : MonoBehaviour
{
    void Update()
    {
        if (Input.GetMouseButton(0))
        {
            Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);

            if (Physics.Raycast(ray, out RaycastHit terrainHit))
            {
                transform.up = terrainHit.normal;
            }
        }
    }
}

普通棒

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