using System.Collections; using System.Collections.Generic; using UnityEngine; public class Floater : MonoBehaviour { private GerstnerWave waveGenerator; public float boatOffset = 0.0f; // new variable private Rigidbody rb; private void Start() { waveGenerator = FindObjectOfType(); rb = GetComponent(); } 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)); } }