Answer the question
In order to leave comments, you need to log in
Unity3D | How to restrict character movement in 3D scene?
I am writing a toy. I would like the character not to fly beyond certain boundaries. The camera follows the character (put the camera into the character as a dependent object in the hierarchy window).
There is a control script. How, using the code, to limit the movement of the character on the stage?
public class PlayerControl : MonoBehaviour
{
public float speedMove; // Скорость передвижения
private float gravityForce; // гравитации персонажа
public float gravityForceSpeed; // скорость гравитации.
private Vector3 moveVector; // Вектор движения
public float jumpForce;
private CharacterController ch_controller; //Ссылка на компонент
private void Start()
{
ch_controller = GetComponent<CharacterController>();
}
private void Update()
{
CharacterMove();
GamingGravity();
}
//Метод перемещения персонажа по сцене.
private void CharacterMove()
{
moveVector = Vector3.zero;
moveVector.x = Input.GetAxis("Horizontal") * speedMove;
moveVector.z = Input.GetAxis("Vertical") * speedMove;
// moveVector.y -= gravityForceSpeed;
moveVector.y =gravityForce;
ch_controller.Move(moveVector * Time.deltaTime);
}
//Метод гравитации.
private void GamingGravity()
{
if(!ch_controller.isGrounded) gravityForce-=gravityForceSpeed * Time.deltaTime;
else gravityForce = -1f;
if (Input.GetKey(KeyCode.Space)) gravityForce = jumpForce;
}
Answer the question
In order to leave comments, you need to log in
Determine the coordinates of the scene borders (the borders you need) and check if the object is outside this border. If so, then return the character to the position of the extreme coordinates.
public int max_x;
void Update(){
if(this.transform.position.x > max_x)
this.transform.position = new Vector(max_x, this.transform.position.y,this.transform.position.z);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question