You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Unity运行时碰撞推动3D Mesh修改及网格弯曲形变技术求助

Hey there! Let's tackle your mesh deformation questions with practical examples and explanations tailored to your needs.

实现指定区域的网格弯曲形变

First, let's address the targeted mesh bending like the yellow area in your GIF. The core idea is to modify vertex positions based on their distance to a target zone, rather than relying on mouse clicks. Here's a reusable Unity C# script that does this:

using UnityEngine;

[RequireComponent(typeof(MeshFilter))]
public class TargetedMeshBender : MonoBehaviour
{
    [Header("Deformation Settings")]
    public Transform targetZone; // Assign your yellow area transform here
    public float bendStrength = 0.5f; // How much the mesh bends
    public float influenceRadius = 2f; // Area around target that affects the mesh

    private Mesh originalMesh;
    private Vector3[] originalVertices;
    private MeshFilter meshFilter;

    void Start()
    {
        meshFilter = GetComponent<MeshFilter>();
        // Make sure the mesh is readable (enable this in Import Settings for your mesh asset)
        originalMesh = meshFilter.mesh;
        originalVertices = originalMesh.vertices.Clone() as Vector3[];
    }

    void Update()
    {
        UpdateMeshBending();
    }

    void UpdateMeshBending()
    {
        Vector3[] deformedVertices = originalVertices.Clone() as Vector3[];

        // Convert target position to local space of the mesh
        Vector3 targetLocalPos = transform.InverseTransformPoint(targetZone.position);

        for (int i = 0; i < deformedVertices.Length; i++)
        {
            float distanceToTarget = Vector3.Distance(deformedVertices[i], targetLocalPos);
            
            // Only modify vertices within the influence radius
            if (distanceToTarget <= influenceRadius)
            {
                // Calculate bending factor (closer = more bend)
                float bendFactor = 1 - (distanceToTarget / influenceRadius);
                
                // Bend towards the target zone's forward direction (adjust this based on your desired bend axis)
                Vector3 bendDirection = transform.TransformDirection(targetZone.forward);
                deformedVertices[i] += bendDirection * bendFactor * bendStrength;
            }
        }

        // Apply the modified vertices back to the mesh
        originalMesh.vertices = deformedVertices;
        originalMesh.RecalculateNormals();
        originalMesh.RecalculateBounds();
        meshFilter.mesh = originalMesh;
    }
}

How this works:

  • We cache the original vertex positions on start so we can reset or recalculate deformations every frame.
  • For each vertex, we check if it's within the influenceRadius of your target zone.
  • Vertices closer to the target get a stronger bend, using a falloff factor based on distance.
  • Adjust bendDirection to match how you want the mesh to curve (e.g., use targetZone.up if you want upward bending).

Setup Tips:

  1. Enable Read/Write Enabled in your mesh asset's Import Settings (this is required to modify vertices at runtime).
  2. Assign your yellow area's Transform to the targetZone field in the Inspector.
  3. Tweak bendStrength and influenceRadius until you get the curvature you want.

运行时通过碰撞推动修改3D Mesh

For collision-driven mesh deformation, we can extend the logic above to respond to physical impacts. Here's a modified script that pushes mesh vertices when another object collides with it:

using UnityEngine;

[RequireComponent(typeof(MeshFilter), typeof(Collider))]
public class CollisionMeshDeformer : MonoBehaviour
{
    [Header("Deformation Settings")]
    public float pushStrength = 0.1f;
    public float pushRadius = 1.5f;

    private Mesh originalMesh;
    private Vector3[] originalVertices;
    private MeshFilter meshFilter;

    void Start()
    {
        meshFilter = GetComponent<MeshFilter>();
        originalMesh = meshFilter.mesh;
        originalVertices = originalMesh.vertices.Clone() as Vector3[];
        // Ensure the collider is set to Convex if using Rigidbody
        if (GetComponent<Rigidbody>() != null)
        {
            GetComponent<Collider>().convex = true;
        }
    }

    void OnCollisionStay(Collision collision)
    {
        foreach (ContactPoint contact in collision.contacts)
        {
            DeformMeshAtPoint(contact.point);
        }
    }

    void DeformMeshAtPoint(Vector3 worldPoint)
    {
        Vector3[] deformedVertices = originalMesh.vertices.Clone() as Vector3[];
        Vector3 localPoint = transform.InverseTransformPoint(worldPoint);

        for (int i = 0; i < deformedVertices.Length; i++)
        {
            float distance = Vector3.Distance(deformedVertices[i], localPoint);
            
            if (distance <= pushRadius)
            {
                float pushFactor = 1 - (distance / pushRadius);
                // Push vertices away from the collision point
                Vector3 pushDirection = (deformedVertices[i] - localPoint).normalized;
                deformedVertices[i] += pushDirection * pushFactor * pushStrength;
            }
        }

        originalMesh.vertices = deformedVertices;
        originalMesh.RecalculateNormals();
        originalMesh.RecalculateBounds();
        meshFilter.mesh = originalMesh;
    }
}

Key Notes:

  • This uses OnCollisionStay to detect ongoing collisions and deform the mesh at each contact point.
  • Vertices within pushRadius of the collision point are pushed away from the impact direction.
  • If your mesh uses a Rigidbody, set the collider to Convex so Unity can detect collisions properly.
  • For better performance with high-poly meshes, consider adding a cooldown or updating the mesh on fixed timesteps instead of every frame.

Additional Tips:

  • For smoother, more organic deformations, you can integrate vertex weights or blend shapes, but the scripts above are perfect for quick, runtime modifications.
  • To reset the mesh to its original shape, just assign the cached originalVertices back to the mesh's vertices array.

内容的提问来源于stack exchange,提问作者Kurai Kun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.08 12:07:46