Unity3D實(shí)現(xiàn)射線使物體移動
更新時間:2019年12月25日 09:36:44 作者:leonardo_Davinci
這篇文章主要為大家詳細(xì)介紹了Unity3D實(shí)現(xiàn)射線使物體移動,文中示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實(shí)例為大家分享了Unity3d如何通過射線使物體移動的具體代碼,供大家參考,具體內(nèi)容如下

實(shí)現(xiàn):
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RayTest : MonoBehaviour {
//設(shè)置射線在Plane上的目標(biāo)點(diǎn)target
private Vector3 target;
// Use this for initialization
void Start () {
//初始化目標(biāo)點(diǎn)與自身的點(diǎn)重合
target = transform.position;
}
// Update is called once per frame
void Update () {
//當(dāng)點(diǎn)擊鼠標(biāo)左鍵的時候創(chuàng)建一條射線
if(Input.GetMouseButton(0))
{
//定義射線
Ray m_ray;
//保存碰撞信息
RaycastHit m_hit;
//創(chuàng)建一條從攝像機(jī)發(fā)出經(jīng)過屏幕上的鼠標(biāo)點(diǎn)的一條射線
m_ray = Camera.main.ScreenPointToRay(Input.mousePosition);
//判斷射線是否碰撞到物體
if(Physics.Raycast(m_ray,out m_hit))
{
//判斷碰撞到的是不是Plane
if(m_hit.transform.name=="Plane")
{
//把目標(biāo)點(diǎn)target設(shè)置為m_hit.point,//并使物體要處于Plane上所以Y軸為0.5f
target = new Vector3(m_hit.point.x, 0.5f, m_hit.point.z);
}
}
}
Move(target);
}
//移動方法
void Move(Vector3 target)
{
if (Vector3.Distance(transform.position, target) > 0.1f)
{
transform.position = Vector3.Lerp(transform.position, target,Time.deltaTime);
}
//如果物體的位置和目標(biāo)點(diǎn)的位置距離小于 0.1時直接等于目標(biāo)點(diǎn)
else
transform.position = target;
}
}
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
C# Fiddler插件實(shí)現(xiàn)網(wǎng)站離線瀏覽功能
本文主要介紹了C# Fiddler插件實(shí)現(xiàn)網(wǎng)站離線瀏覽功能的原理與方法。具有很好的參考價值,下面跟著小編一起來看下吧2017-02-02

