using System.Collections; using System.Collections.Generic; using UnityEngine; public class Floater : MonoBehaviour { public GerstnerWave waveGenerator; public float boatOffset = 0.0f; // new variable private Rigidbody rb; private void Start() { rb = GetComponent(); } void Update() { float waveNumber = 2.0f * Mathf.PI / waveGenerator.waveLength; float phaseConstant = waveGenerator.speed * waveNumber; // Convert the boat's world position to the wave's local position Vector3 localPosition = waveGenerator.transform.InverseTransformPoint(rb.position); float dotProduct = Vector2.Dot(new Vector2(localPosition.x, localPosition.z), waveGenerator.direction); float wavePhase = waveNumber * dotProduct + phaseConstant * Time.time; // Calculate the new height float 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 Vector3 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 Quaternion targetRotation = Quaternion.FromToRotation(transform.up, normal) * transform.rotation; rb.MoveRotation(Quaternion.Slerp(transform.rotation, targetRotation, Time.deltaTime * waveGenerator.speed)); } }