Regarding Space shooter boundary constraints

Hi,

In space shooter lesson, before instructor telling about Math.clamp, I wrote a simple snippet to constrain the ship. But the following code is not working. Although it is updating the values that I declare but there is some problem which I do not know. Here is the code. I have written only to constrain it from one side which is +6.0 value in x dimension. I have written a simple if statement but that if condition is not being entered into.
Let me know what am I doing wrong in this approach. Thanks.

using UnityEngine;
using System.Collections;

public class PlayerController : MonoBehaviour {

public float speed;

private Rigidbody rb;


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);
    Vector3 pos = rb.position;
    print(pos.x);
    if (pos.x == 6.0f)
        #print("success");   # uncomment to check if condition is being entered.
        rb.AddForce(movement * 0.0f);
   
}   

}

You can’t generally compare floating point values to something specific using ==. In your example, the chance of pos.x being exactly 6.0 is very low. There are a couple of ways you can handle this. You can use Mathf.Approximately which will allow values very close to 6.0 (e.g. 6.0001, 5.99992) to be “equal” to 6.

A better choice in your example is to look for a value >= 6…

if (pos.x >= 6.0f)
{
    ... your stuff...
}

You would want to set the object’s x position to 6 inside the ifto force it back within the bounds. What you’ve effectively done now is to implement the clamping function. :slight_smile: