78 lines
2.7 KiB
C#
78 lines
2.7 KiB
C#
using UnityEngine;
|
|
|
|
/// <summary>
|
|
/// Makes this object follow a target (bottleTransform) horizontally, optionally using a wobble offset for vertical movement.
|
|
/// </summary>
|
|
public class RockFollower : MonoBehaviour
|
|
{
|
|
[Header("References")]
|
|
public Transform bottleTransform;
|
|
public WobbleBehavior bottleWobble;
|
|
|
|
[Header("Movement Settings")]
|
|
public float followStiffness = 4f;
|
|
/// <summary>
|
|
/// Whether to use the wobble offset for vertical movement.
|
|
/// </summary>
|
|
public bool useWobbleOffset = true;
|
|
/// <summary>
|
|
/// The vertical distance between the rock and the bottle.
|
|
/// </summary>
|
|
[SerializeField] private float verticalDistance = 6f;
|
|
|
|
private float velocityX; // For SmoothDamp
|
|
|
|
#if UNITY_EDITOR
|
|
/// <summary>
|
|
/// Called in editor when properties are changed.
|
|
/// Updates the object's position when verticalDistance is modified.
|
|
/// </summary>
|
|
private void OnValidate()
|
|
{
|
|
// Only update position if playing or in prefab mode
|
|
if (Application.isPlaying || UnityEditor.PrefabUtility.IsPartOfPrefabAsset(this))
|
|
return;
|
|
|
|
if (bottleTransform != null)
|
|
{
|
|
// Calculate the new Y position based on bottle's position and the updated verticalDistance
|
|
float newY = bottleTransform.position.y - verticalDistance;
|
|
|
|
// Apply the wobble offset if enabled
|
|
if (useWobbleOffset && bottleWobble != null)
|
|
{
|
|
newY += bottleWobble.VerticalOffset;
|
|
}
|
|
|
|
// Update only the Y position, keeping X and Z unchanged
|
|
transform.position = new Vector3(transform.position.x, newY, transform.position.z);
|
|
|
|
// Mark the scene as dirty to ensure changes are saved
|
|
UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(UnityEngine.SceneManagement.SceneManager.GetActiveScene());
|
|
}
|
|
}
|
|
#endif
|
|
|
|
void Update()
|
|
{
|
|
if (bottleTransform == null) return;
|
|
|
|
// Target horizontal position is bottle's X
|
|
float targetX = bottleTransform.position.x;
|
|
float currentX = transform.position.x;
|
|
|
|
// Smoothly follow bottle's X with stiffer motion
|
|
float newX = Mathf.SmoothDamp(currentX, targetX, ref velocityX, 1f / followStiffness);
|
|
|
|
// Calculate Y position based on bottle's position and vertical distance
|
|
float newY = bottleTransform.position.y - verticalDistance;
|
|
if (useWobbleOffset && bottleWobble != null)
|
|
{
|
|
newY += bottleWobble.VerticalOffset;
|
|
}
|
|
|
|
// Set new position (only X and Y, keep Z)
|
|
transform.position = new Vector3(newX, newY, transform.position.z);
|
|
}
|
|
}
|