I have a game object that has specific boundaries. However, when I have the object meet the boundaries, the object doesn't stop the way it's supposed to, it continues to move past the set boundaries. Can anyone explain why this would be happening and how to fix it?
Player Object public variables
C#
using UnityEngine;
using System.Collections;
public class PlayerController:MonoBehaviour{
public Rigidbody player;
public float bankSpeed;
public float bankRotation;
public float pitchSpeed;
public float pitchAngle;
public float xMin, xMax, yMin, yMax;
public ChangeCamera changeCamera;
void Start(){
player = GetComponent<Rigidbody>();
changeCamera.isThirdPersonView = false;
changeCamera.isTopDownView = false;
}
void FixedUpdate(){
if(changeCamera.isThirdPersonView == true){
changeCamera.isTopDownView = false;
thirdPersonControls();
}
if(changeCamera.isTopDownView == true){
changeCamera.isThirdPersonView = false;
topDownControls();
}
}
void topDownControls(){
float moveVertical = Input.GetAxis("Vertical");
float moveHorizontal = Input.GetAxis("Horizontal");
Vector3 bank = new Vector3(moveHorizontal, 0f, 0f);
Vector3 moveForward = new Vector3(0f, 0f, moveVertical);
player.AddForce(bank * bankSpeed);
player.AddForce(moveForward * pitchSpeed);
topDownRotation();
}
void thirdPersonControls(){
float moveVertical = Input.GetAxis("Vertical");
float moveHorizontal = Input.GetAxis("Horizontal");
Vector3 bank = new Vector3(moveHorizontal, 0f, 0f);
Vector3 pitch = new Vector3(0f, moveVertical, 0f);
player.AddForce(bank * bankSpeed);
player.AddForce(pitch * pitchSpeed);
thirdPersonRotate();
}
void topDownRotation(){
player.rotation = Quaternion.Euler(0f, 0f, (player.velocity.x * -bankRotation));
player.position = new Vector3(Mathf.Clamp(player.position.x, -15.25f, 15.25f), 0f, Mathf.Clamp(player.position.z, 1f, 18.25f));
}
void thirdPersonRotate(){
player.rotation = Quaternion.Euler((player.velocity.y * -pitchAngle), 0f, (player.velocity.x * -bankRotation));
player.position = new Vector3(Mathf.Clamp(player.position.x, xMin, xMax), Mathf.Clamp(player.position.y, yMin, yMax), 0f);
}
}
Basically, the way it works is, the player moves in any direction(up, down, left, right) and when they hit the edge of the screen, they're supposed to stop, which they do, however, if they continue to press the button that moves them, they'll continue to move off screen, very slowly. How do I prevent this from happening?