OldBlueWater/BlueWater/Assets/02.Scripts/WaterAndShip/Gerstner wave/Floater.cs

49 lines
1.9 KiB
C#

using System.Collections;
using System.Collections.Generic;
using Sirenix.OdinInspector;
using UnityEngine;
[RequireComponent(typeof(Rigidbody))]
public class Floater : MonoBehaviour
{
private GerstnerWave waveGenerator;
[InfoBox("배가 얼마나 물에 잠길지 정합니다. 낮을수록 물에 잠깁니다.")]
public float boatOffset = 0.0f; // new variable
private Rigidbody rb;
private void Start()
{
waveGenerator = FindObjectOfType<GerstnerWave>();
rb = GetComponent<Rigidbody>();
}
void Update()
{
var waveNumber = 2.0f * Mathf.PI / waveGenerator.waveLength;
var phaseConstant = waveGenerator.speed * waveNumber;
// Convert the boat's world position to the wave's local position
var localPosition = waveGenerator.transform.InverseTransformPoint(rb.position);
var dotProduct = Vector2.Dot(new Vector2(localPosition.x, localPosition.z), waveGenerator.direction);
var wavePhase = waveNumber * dotProduct + phaseConstant * Time.time;
// Calculate the new height
var newY = waveGenerator.amplitude * Mathf.Sin(wavePhase) + boatOffset;
localPosition.y = newY;
// Convert the position back to world coordinates
rb.MovePosition(waveGenerator.transform.TransformPoint(localPosition));
// Calculate the wave's normal at the boat's position
var normal = new Vector3(
-waveGenerator.amplitude * waveNumber * waveGenerator.direction.x * Mathf.Cos(wavePhase),
1.0f,
-waveGenerator.amplitude * waveNumber * waveGenerator.direction.y * Mathf.Cos(wavePhase)
).normalized;
// Rotate the boat to align with the wave's normal
var targetRotation = Quaternion.FromToRotation(transform.up, normal) * transform.rotation;
rb.MoveRotation(Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * waveGenerator.speed));
}
}