The program is in a top down view, with Y going up (or forward depending upon how you see it), and X going from left to right based on the camera view. I am attempting to set the minimum and maximum values of my main character's x/y-axis movement through the float "clamp", under the struct "Mathf".
When my ship passes the minimum/maximum value on either axis, it doesn't stop it. If you release the movement key after passing the point, the character will appear directly on the minimum/maximum point that was passed. See the gif below.
Gif here http://gph.is/22fdHv4
Below is the current script running for both player movement and the boundary, attached to the main character.
using UnityEngine;
using System.Collections;
public class ShipMovement : MonoBehaviour {
public float xMin;
public float xMax;
public float yMin;
public float yMax;
public float speed = 2f;
public float shotSpeed = 4f;
public float nextFire1;
public float nextFire2;
//Animator anim;
public GameObject shot;
public Transform shotSpawn;
public float fireRate = 0.25f;
void Start () {
//anim = GetComponent<Animator> ();
}
void FixedUpdate () {
GetComponent<Rigidbody> ().position = new Vector3 (
Mathf.Clamp (transform.position.x, xMin, xMax ),
Mathf.Clamp (transform.position.y, yMin, yMax),
0.0f
);
if (Input.GetKey (KeyCode.W)) {
transform.Translate (Vector2.up * speed * Time.deltaTime);
//anim.SetBool ("moving", true);
}
if (Input.GetKey (KeyCode.S)) {
transform.Translate (Vector2.down * speed * Time.deltaTime);
//anim.SetBool ("moving", true);
}
if (Input.GetKey (KeyCode.A)) {
transform.Translate (Vector2.left * speed * Time.deltaTime);
//anim.SetBool ("moving", true);
}
if (Input.GetKey (KeyCode.D)) {
transform.Translate (Vector2.right * speed * Time.deltaTime);
//anim.SetBool ("moving", true);
} else {
//anim.SetBool ("moving", false);
}
if (Input.GetKey (KeyCode.Space) && Time.time > nextFire1)
{
nextFire1 = Time.time + fireRate;
Instantiate(shot, shotSpawn.position, shotSpawn.rotation);
}
if (Input.GetKey (KeyCode.X) && Time.time > nextFire2) {
nextFire2 = Time.time + fireRate;
Instantiate (shot, shotSpawn.position, shotSpawn.rotation);
}
if (gameObject == null) {
Application.Quit ();
}
}
}
Although I am not sure, I suspect it may have something to with the way I am controlling the movement. I have had issues with what I have written in the past, especially with animations and moving left/right while also moving up/down. (Hence why I have all of the animation code commented out, and I am using a Capsule instead of a ship).
If anything else is needed, I can provide it.