Clamp Problems

Hey guys. So I’m making a simple game where objects will be falling from the sky, and you are a “bucket” trying to catch them. You can only move horizontally, and you cannot go out of bounds (Camera)

I’ve tried looking for something that I can understand but I just keep finding long complex ways of doing it that don’t even use clamp.

I’ve thought about just using 2 colliders on both sides of the bucket, and having a collider on the outside of the map (Left and right) but I just want to do this with pure code and not cheat with box colliders.

What’s the simplest way of saying “You can only move horizontally within x amount units”?

This is all I have so far…

New to coding and unity so a description would be much appreciated. Thanks!

using UnityEngine;
using System.Collections;

public class PlayerMov : MonoBehaviour
{
    public float Speed = 50.0f;
    public float MinClamp = 5.0f;
    public float MaxClamp = 5.0f;



    void Start ()
    {

    }
   

    void Update ()
    {

        if (Input.GetKey (KeyCode.LeftArrow))
        {
            transform.position -= transform.right * Speed * Time.deltaTime;
        }

        else if (Input.GetKey (KeyCode.RightArrow))
        {
            transform.position += transform.right * Speed * Time.deltaTime;
        }

   
    }
}
void Update()
{
    // <Your input code>

    transform.position = new Vector3(
        Mathf.Clamp(transform.position.x, minClamp, maxClamp),
        transform.position.y,
        transform.position.z
    );
}

Move, then clamp.

This just teleports the player to the right corner of the screen for whatever reason

In your code above, you have minClamp and maxClamp set to the same value. Make sure you set them correctly in the inspector.