Moving on uneven terrain issue

Hi All:

I am starting my first Unity first person game. I have an fbx terrain that has a “ramp” to another part of the level. And currently moving the character around using the Translate function. The terrain and player both have mesh colliders attached. Now when the character moves, it is stuck in the same y position. Which I understand why that’s happening, so my question is how can I change the y position based on the terrain. So far I have tried the below code which I intend for it to place the character above the ground; with out luck. Can someone point me the right direction?

                transform.Translate(characterLoc * (input.Running() ? walkSpeed * runMultiplier : walkSpeed));
		
		transform.Rotate(characterRot * rotationSpeed);
		
		RaycastHit hit;
        if (Physics.Raycast(transform.position, -Vector3.up, out hit)) {
			if (hit.collider.gameObject.name == "ground") {
				float distanceToGround = hit.distance;
				transform.Translate(new Vector3(transform.position.x, transform.position.y + distanceToGround, transform.position.z));
			}
		}
		else if (Physics.Raycast(transform.position, Vector3.up, out hit)) {
			if (hit.collider.gameObject.name == "ground") {
				float distanceToGround = hit.distance;
				transform.Translate(new Vector3(transform.position.x, transform.position.y + distanceToGround, transform.position.z));
			}
		}

is your character just staying on the same Y with that script?

instead of the line

transform.Translate(new Vector3(transform.position.x, transform.position.y + distanceToGround, transform.position.z));

you can write

transform.position.y = hit.point.y + (height of legs);

I think that would make an object always stuck to the floor under it as if it had 1000000000 gravity:))

You should be able to get pretty accurate movement just with a simple capsule collider on the character. As long as you are using a Rigidbody with gravity enabled.

This will solve your y-axis floating problem, but you may begin to experience slight sliding effects on the x and y axis if you are on a hill. So you might need to cast a ray downwards and then manually keep the character in that spot unless they use movement keys.

I never used their built in character controller features, because when I first started I was so new at coding that I wanted to learn it from scratch.

But as far as I can tell it takes a lot of extra work to set up realistic movements from scratch. Kind of disappointing considering 99% of games probably require this. Perhaps their character controller features would solve this but I never tried it.

The issue was that I was using two mesh colliders one for the terrain and one for the player. Oppps. Noob mistake I guess.