using UnityEngine;
using System.Collections.Generic;
public class ScatterAndRestore : MonoBehaviour
{
private Dictionary<Transform, Vector3> originalPositions; // 存储初始位置
private Dictionary<Transform, Vector3> relativePositions; // 存储相对于父物体中心的位置
private bool scattered = false; // 标记是否已散开
public float scatterMultiplier = 2.0f; // 散开的倍数
void Start()
{
originalPositions = new Dictionary<Transform, Vector3>();
relativePositions = new Dictionary<Transform, Vector3>();
// 存储初始位置和相对位置
foreach (Transform child in transform)
{
originalPositions[child] = child.position;
relativePositions[child] = child.localPosition; // 相对于父物体的位置
}
}
void Update()
{
// 当按下"S"键时,切换散开和还原状态
if (Input.GetKeyDown(KeyCode.S))
{
if (scattered)
{
Restore();
scattered = false;
}
else
{
Scatter();
scattered = true;
}
}
}
// 散开子节点
private void Scatter()
{
foreach (Transform child in transform)
{
child.localPosition = relativePositions[child] * scatterMultiplier;
}
}
// 还原子节点
private void Restore()
{
foreach (Transform child in transform)
{
child.position = originalPositions[child];
}
}
}