R
R
Relayz2020-08-17 21:06:01
Unity
Relayz, 2020-08-17 21:06:01

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?

the code
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

1 answer(s)
Z
zZaKko, 2020-08-18
@Relayz

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);
}

ps and so on for each border (max_x, min_x, max_y, min_y, max_z, min_z).

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question