Space Shooter Tutorial - Mathf.Clamp behaving strangely

I’m trying to set the boundaries for this game so the spaceship doesn’t move outside the play area. I have copied the code exactly (although I have had to make the changes set in the unity 5 update guide) but the spaceship doesn’t stop at the boundaries I set, it just slows down greatly but continues moving past the boundaries I’ve set. Can anyone please help?

My code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

[System.Serializable]
public class Boundary
{
    public float xMin, xMax, zMin, zMax;
}

public class PlayerController : MonoBehaviour {

    private Rigidbody rb;

    public float speed;
    public Boundary boundary;

    void Start ()
    {
        rb = GetComponent<Rigidbody>();
    }

    void FixedUpdate ()
    {
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
        rb.AddForce (movement * speed);

        rb.position = new Vector3

        (
                Mathf.Clamp (rb.position.x, boundary.xMin, boundary.xMax),
                0.0f,
                Mathf.Clamp (rb.position.z, boundary.zMin, boundary.zMax)

        );
    }
}

It’s important to realize that the physics update happens after your FixedUpdate code runs. In this case, it looks like your ship still has velocity - continually increasing velocity, at that. So, you’re setting its position, but then its velocity in the immediately-following physics update is carrying it past the position you set.

You should set its velocity to 0 if it’s outside your acceptable range. This is slightly annoying to code, though (not hard, just annoying).

A better way is to simply put 4 (presumably invisible) box colliders as the boundary of your play area, rather than using code at all. (If other objects need to pass through these boundaries, you can set them to their own layer and tweak the layer collision settings in Physics Settings.)

I was having the same issue but if you change the rb.AddForce (movement * speed); to rb.velocity = movement * speed; this should sort this out.