- Home /
Question by
jisase · 6 days ago ·
c#meshmeshesdeformationmesh vertices
How to deform a mesh at runtime?
Hi, I am trying to modify a mesh at run time based on the mouse position. It is the first time that I work with meshes and something is happening to me that I don't understand, if someone can help me I would appreciate it very much.
this is my code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class MeshController : MonoBehaviour
{
[Header("CUSTOM VALUES")]
public float radius = 2f;
public float deformationStrength = 2f;
public float smoothingFactor = 2f;
[Header("REFRENCES")]
public GameObject brush;
public Camera cam;
private Mesh mesh;
private Vector3[] verticies, modifiedVerts;
private void Start()
{
if(cam == null) cam = Camera.main;
if (brush == null) brush = GameObject.FindGameObjectWithTag("Brush");
mesh = GetComponentInChildren<MeshFilter>().mesh;
verticies = mesh.vertices;
modifiedVerts = mesh.vertices;
}
private void Update()
{
RaycastHit hit;
Ray ray = cam.ScreenPointToRay(Input.mousePosition);
if (Physics.Raycast(ray, out hit, Mathf.Infinity))
{
for (int v = 0; v < modifiedVerts.Length; v++)
{
Vector3 distance = modifiedVerts[v] - hit.point;
Debug.DrawRay(modifiedVerts[v], hit.point, Color.red);
float force = deformationStrength / (1f + hit.point.sqrMagnitude);
if (distance.sqrMagnitude < radius)
{
if (Input.GetMouseButton(0))
{
modifiedVerts[v] += (Vector3.up * force) / smoothingFactor;
}
else if (Input.GetMouseButton(1))
{
modifiedVerts[v] += (Vector3.down * force) / smoothingFactor;
}
}
}
brush.transform.position = hit.point;
}
RecalculateMesh();
}
void RecalculateMesh()
{
mesh.vertices = modifiedVerts;
GetComponentInChildren<MeshCollider>().sharedMesh = mesh;
mesh.RecalculateNormals();
}
private void OnDrawGizmosSelected()
{
Gizmos.color = Color.yellow;
Gizmos.DrawWireSphere(brush.transform.position, radius);
}
}
When I run it, the ray that I draw inside the for indicates me that it is only returning me a vertex and only when I place myself over it is that the mesh is modified and I should be able to modify each vertex of the mesh. What am I doing wrong?
And I will leave a link to a gift: https://drive.google.com/file/d/1owGRkiKxZS9ifd4jdRS2IUjcD-dyGx_E/view?usp=sharing
capture.png
(353.7 kB)
Comment
sorry it is not returning only one vertex, what is happening is that all vertices are in the same place.