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,完成!
  • 1
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值