Left–Right Movement (Unity C#)
Got you — here’s a clean 2D‑friendly left/right movement script that behaves exactly how you expect in a 2D Unity project. No 3D vectors, no physics weirdness, just pure 2D motion.
🎮 2D Left–Right Movement (Unity C#)
using UnityEngine;
public class LeftRightMover2D : MonoBehaviour
{
[Header("Movement Settings")]
public float speed = 3f; // Movement speed
public float moveDistance = 2f; // How far from the start point
private Vector2 startPos;
private int direction = 1;
void Start()
{
startPos = transform.position;
}
void Update()
{
// Move horizontally in 2D
transform.Translate(Vector2.right * direction * speed * Time.deltaTime);
// Flip direction when reaching bounds
if (Vector2.Distance(startPos, transform.position) >= moveDistance)
{
direction *= -1;
}
}
}
🧠Why this works well in 2D
- Uses Vector2 instead of Vector3
- Movement stays strictly on the X‑axis
- No Rigidbody2D required (unless you want physics‑based motion)
- Perfect for enemies, platforms, hazards, or decorative objects
⚡ Want a different flavor?
I can give you versions for:
- Player‑controlled left/right movement (A/D or arrows)
- Rigidbody2D‑based movement
- Smooth sine‑wave bobbing
- Patrol between two specific points
- Auto‑flip sprite when changing direction
Comments