Mathf.Clamp help required

Hello! I’m doing a project from this book called “Unity Game Development in 24 Hours” by Ben Tristem and Mike Geig. In Chapter 15 we use Mathf.Clamp to help keep the ship on screen. Here is the code -
using UnityEngine;
using System.Collections;

public class ShipControlScript : MonoBehaviour {
    public float playerSpeed = 10f;
    public GameControl gameController;
    public GameObject bulletPrefab;
    public float reloadTime = 0.5f; //Bullets can fire every 0.5 seconds
    private bool invert = false;
    private float elapsedTime = 0;

    // Update is called once per frame
    void Update() {
        elapsedTime += Time.deltaTime;

        //Move player from left to right
        float xMovement = Input.GetAxis("Horizontal") * playerSpeed * Time.deltaTime;
        float xPosition = Mathf.Clamp(xMovement, -7f, 7f); //Keeps ship on screen

        if (invert){
            transform.Translate(xPosition * -1, 0f, 0f);
        }
        else{
            transform.Translate(xPosition, 0f, 0f);
        }

        if (Input.GetButtonDown("Shoot") && elapsedTime > reloadTime) {
            Vector3 spawnPos = transform.position;
            spawnPos += new Vector3(0, 1f, 0);
            Instantiate(bulletPrefab, spawnPos, Quaternion.identity);

            invert = !invert;

            elapsedTime = 0f;
        }

        if (reloadTime > 0.2f){
            reloadTime -= Time.deltaTime / 300;
        }
    }

    void OnTriggerEnter2D (Collider2D other){
        gameController.PlayerDied();
    }
}

Thing is that ship doesn’t stay within -7f and 7f. It continues on and on. I even copy pasted the code that they provided and the ship still isn’t restricted. Any idea why? Thanks for any help in advance.

If that’s exactly how the code is written, there’s a mistake in the book.
You’re using clamp to make sure that the value of xPosition is always within the range (-7,7):

float xPosition = Mathf.Clamp(xMovement, -7f, 7f);

But “xPosition” does not represent the position of the ship on the screen. It is used to determine the amount by which the ship moves each frame:

transform.Translate(xPosition, 0f, 0f);

I have found pretty much every book related to Unity disappointing and badly-edited. I recommend you click the Learn tab at the top of this page to follow the official tutorials instead.