Unity – 让物体紧贴地面移动

 

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DetectGround : MonoBehaviour {

	private float boxCol;

	// Use this for initialization
	void Start () {
		boxCol = gameObject.GetComponent<BoxCollider> ().bounds.size.y;

	}
	
	// Update is called once per frame
	void Update () {
		Ray ray = new Ray (transform.position, -transform.up);
		RaycastHit hit;

		if (Physics.Raycast(ray, out hit)){
			Debug.Log("hello");
			transform.position = new Vector3(transform.position.x, hit.point.y + boxCol / 2, transform.position.z);
			transform.rotation = Quaternion.FromToRotation (Vector3.up, hit.normal);
		}
	}
}