using UnityEngine; public class SinTwoWay2D : MonoBehaviour { public float distance = 5.0f; public float frequency = 5.0f; public float speed = 0.1f; public float yMax = 1.0f; bool facingRight = true; Vector3 pos; Vector3 move; Vector3 localScale; void Start() { pos = transform.position; move = transform.position; localScale = transform.localScale; } void FixedUpdate() { CheckWhereToFace(); if (facingRight) { MoveRight(); } else { MoveLeft(); } } void CheckWhereToFace() { if (transform.position.x < pos.x - distance) { facingRight = true; } else if (transform.position.x > pos.x + distance) { facingRight = false; } if ((facingRight && localScale.x < 0) || (!facingRight && localScale.x > 0)) { localScale.x *= -1; } transform.localScale = localScale; } void MoveRight() { move += transform.right * speed; transform.position = move + transform.up * Mathf.Sin(Time.time * frequency) * yMax; } void MoveLeft() { move -= transform.right * speed; transform.position = move + transform.up * Mathf.Sin(Time.time * frequency) * yMax; } }