HCI/Unity
[Unity] Mesh 누르면 변형하기 / 물체 찌그러트리기 / 물체 매쉬 변형 / Mesh Deformation
sillon
2024. 12. 11. 16:04
728x90
반응형
https://catlikecoding.com/unity/tutorials/mesh-deformation/
Mesh Deformation, a Unity C# Tutorial
A Unity C# scripting tutorial in which you will deform a mesh, turning it into a stress ball.
catlikecoding.com
여기서 있는 코드를 변형했습니당
방법은 초간단
3D 프로젝트 빌드 후, 위의 사이트에서 패키지를 받아주고, 임포트해줍니다
저는 Move Vertices 를 변형해서 써보겠습니다
패키지 받고 더블클릭하면 자동으로 유니티에서 화면이 뜹니다.
그리고 해당 패키지에서 제공하는 샘플 Scene 을 켜줍니다
이름은 그냥 Scene 이라고 돼있음
여기서 MeshDeformer.cs 코드를 아래와 같이 수정합니다
using UnityEngine;
[RequireComponent(typeof(MeshFilter))]
public class MeshDeformer : MonoBehaviour
{
Mesh deformingMesh;
Vector3[] originalVertices, displacedVertices;
Vector3[] vertexVelocities;
void Start()
{
deformingMesh = GetComponent<MeshFilter>().mesh;
originalVertices = deformingMesh.vertices;
displacedVertices = new Vector3[originalVertices.Length];
for (int i = 0; i < originalVertices.Length; i++)
{
displacedVertices[i] = originalVertices[i];
}
vertexVelocities = new Vector3[originalVertices.Length];
}
void Update()
{
for (int i = 0; i < displacedVertices.Length; i++)
{
UpdateVertex(i);
}
deformingMesh.vertices = displacedVertices;
deformingMesh.RecalculateNormals();
}
void UpdateVertex(int i)
{
Vector3 velocity = vertexVelocities[i];
displacedVertices[i] += velocity * Time.deltaTime;
// 감속을 통해 변위가 천천히 멈추도록 함
vertexVelocities[i] *= 0.9f; // 감속 계수, 0.9로 설정해 조금씩 느려지게 함
}
public void AddDeformingForce(Vector3 point, float force)
{
point = transform.InverseTransformPoint(point);
for (int i = 0; i < displacedVertices.Length; i++)
{
AddForceToVertex(i, point, force);
}
}
void AddForceToVertex(int i, Vector3 point, float force)
{
Vector3 pointToVertex = displacedVertices[i] - point;
float attenuatedForce = force / (1f + pointToVertex.sqrMagnitude);
float velocity = attenuatedForce * Time.deltaTime;
vertexVelocities[i] += pointToVertex.normalized * velocity;
}
}
// 사용 예시:
// 특정 지점에 힘을 가하려면, 다른 스크립트에서 AddDeformingForce 메서드를 호출하여 변형시킬 수 있습니다.
// 예: meshDeformer.AddDeformingForce(충돌 지점, 힘 크기);
728x90
반응형