Unity3D之點擊地形使物體移動到指定位置

新建一個plane物體作爲地形,新建cube和一個腳本Cube1,將該腳本掛到cube上,代碼如下:

[csharp] view plain copy
  1. using UnityEngine;  
  2. using System.Collections;  
  3.   
  4. public class Cube01 : MonoBehaviour   
  5. {  
  6.     private float timeHit;  
  7.   
  8.     void Awake()  
  9.     {  
  10.         timeHit = 0f;  
  11.     }  
  12.   
  13.     void Update()  
  14.     {  
  15.         timeHit += Time.deltaTime;  
  16.         if (Input.GetMouseButton(0) && timeHit > 0.2f)  
  17.         {  
  18.             timeHit = 0f;  
  19.             RaycastHit hit;  
  20.             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);  
  21.             if (Physics.Raycast(ray, out hit))  
  22.             {  
  23.                 if (hit.collider.gameObject.tag == "Terrain")  
  24.                 {  
  25.                     //因爲cube的中心點高0.5,所以Y座標加0.5f  
  26.                     transform.position = new Vector3(hit.point.x, hit.point.y + 0.5f, hit.point.z);  
  27.                 }  
  28.             }  
  29.         }  
  30.     }  
  31. }  

OK,完成!
發佈了56 篇原創文章 · 獲贊 61 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章