Had to create an Exploded view for 3D models for a VR/AR 3D model viewer I was working on. As first instinct I googled to see if someone has made it already for Unity, and sadly left empty handed. So I decided to make one for myself, and it came out pretty well I think.
The Code :
//Coded by Abishek J Reuben
using UnityEngine;
using System.Collections.Generic;
using System;
[Serializable]
public class SubMeshes
{
public MeshRenderer meshRenderer;
public Vector3 originalPosition;
public Vector3 explodedPosition;
}
public class ThreeDModelFunctions : MonoBehaviour
{
#region Variables
public List<SubMeshes> childMeshRenderers;
bool isInExplodedView = false;
public float explosionSpeed = 0.1f;
bool isMoving = false;
#region UnityFunctions
private void Awake()
{
childMeshRenderers = new List<SubMeshes>();
foreach (var item in GetComponentsInChildren<MeshRenderer>())
{
SubMeshes mesh = new SubMeshes();
mesh.meshRenderer = item;
mesh.originalPosition = item.transform.position;
mesh.explodedPosition = item.bounds.center * 1.5f;
childMeshRenderers.Add(mesh);
}
}
private void Update()
{
if (isMoving)
{
if (isInExplodedView)
{
foreach (var item in childMeshRenderers)
{
item.meshRenderer.transform.position = Vector3.Lerp(item.meshRenderer.transform.position, item.explodedPosition, explosionSpeed);
if (Vector3.Distance(item.meshRenderer.transform.position, item.explodedPosition) < 0.001f)
{
isMoving = false;
}
}
}
else
{
foreach (var item in childMeshRenderers)
{
item.meshRenderer.transform.position = Vector3.Lerp(item.meshRenderer.transform.position, item.originalPosition, explosionSpeed);
if (Vector3.Distance(item.meshRenderer.transform.position, item.originalPosition) < 0.001f)
{
isMoving = false;
}
}
}
}
}
#region CustomFunctions
public void ToggleExplodedView()
{
if (isInExplodedView)
{
isInExplodedView = false;
isMoving = true;
}
else
{
isInExplodedView = true;
isMoving = true;
}
}
}
Awesome script! Thank you!
Hi, thank you for your awesome script. Could you give some hints about applying the script on a model. Where we should attach the script? How to wire to a button and what is the requirement for the exploded model (pivot) etc.? Thank you in advance. Peter from Hungary