Going through walls and diving into terrain


I had to make my first question here because i can´t seem to solve the issue i´m having with my project.

I have a scene made with walls, houses, statues, trees etc etc and don´t want to go through them. The terrain i have has Create tree Coliders checked has all the trees are associated to the terrain object.

I´ve also set Mesh Colliders to every object but when I´m in running mode i go through walls and can dive infinitely under the terrain.

I´m using a script for my camera which lets the user fly through the environment but i would like the user to stay at terrain level and not fly:

var lookSpeed = 15.0;
var moveSpeed = 15.0;

var rotationX = 0.0;
var rotationY = 0.0;

function Update ()
    rotationX += Input.GetAxis("Mouse X")*lookSpeed;
    rotationY += Input.GetAxis("Mouse Y")*lookSpeed;
    rotationY = Mathf.Clamp (rotationY, -90, 90);
    transform.localRotation = Quaternion.AngleAxis(rotationX, Vector3.up);
    transform.localRotation *= Quaternion.AngleAxis(rotationY, Vector3.left);
    transform.position += transform.forward*moveSpeed*Input.GetAxis("Vertical");
    transform.position += transform.right*moveSpeed*Input.GetAxis("Horizontal");

I´m really new to Unity and trying to explore it´s workflow but i got stuck in this part of my project. How can i set the user to be at terrain level and use the mouse for several actions in the game and how i avoid going through walls and terrain?

Appreciate your help.

You should attach a character controller to your player character and use CharacterController.Move() or CharacterController.SimpleMove() instead of changing transform.position. The character controller takes collisions into account whereas modifications of transform.position will always be carried out regardless of collisions. You will also need to add a line to account for gravity (i.e. have the character controller accelerate down every frame) so that if your player starts going down a hill, they actually go down instead of just walking straight ahead off of it into the air.

ozone thank you very much for your answer. I didn´t think about adding a character to my project because i want the user to see the environment as a 1st person.

I will have a look into it and be right back when i have something.