- Home /
Crawling around the terrain
Hello, I am a Unity newbie. I have a bug model that crawls around randomly on the X/Z plane, using transform.Translate. I also have a terrain which I have set as a Mesh Collider.
What I want is for the bug to crawl around on the terrain, setting his orientation to match the polygons he's crawling on. However, I'm having difficulty doing this with just the default collision functions.
How can I determine the Z position of the terrain below my bug model? Can I get the orientation of this point, so I can use it as my model's "up" vector?
Answer by UltimateWalrus · Jun 17, 2010 at 11:03 PM
I found a reasonable answer to my problem. I used raycasting to find the proper Y coordinate, then used the normal to set orientation. I still wish I had a better handle on collision detection, but that's for another day I suppose...
var hit : RaycastHit;
if(Physics.Raycast(transform.position+Vector3(0,10,0),Vector3(0,-1,0), hit, 20))
{
transform.position.y = hit.point.y;
groundNormal = hit.normal;
}
Answer by e-bonneville · Jun 17, 2010 at 08:52 PM
Here, this code should do the trick:
function OnCollisionEnter(collision : Collision) {
var contact = collision.contacts[0];
var rot = Quaternion.FromToRotation(Vector3.up, contact.normal);
transform.rotation = rot;
}
It ensures that your bug's Y will be the same as the Y of the last thing it touched.
Thanks for your help. I'm actually having trouble even getting functions like OnCollisionEnter to execute. I gave the terrain a mesh collider. Then, I gave my bug a box collider. Nothing happened. Then, I gave my bug a RidigBody component, and checked Is $$anonymous$$inematic. Still, nothing happened. I even tried making the terrain a RigidBody, to no avail. OnCollisionEnter just doesn't seem to be getting called. Am I missing something? :[
Answer by adamrmoss · Aug 20, 2011 at 02:30 AM
If you're using a CharacterController you need to hook into the OnControllerColliderHit. Here's some C#:
using UnityEngine;
using System.Collections;
public class FollowTerrain : MonoBehaviour
{
public TerrainCollider terrainCollider;
public void OnControllerColliderHit(ControllerColliderHit hit) {
if (hit.collider == terrainCollider) {
var rot = Quaternion.FromToRotation(Vector3.up, hit.normal);
transform.rotation = rot;
}
}
}