溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

Unity3D實(shí)現(xiàn)射線使物體移動(dòng)

發(fā)布時(shí)間:2020-09-25 13:25:02 來(lái)源:腳本之家 閱讀:144 作者:leonardo_Davinci 欄目:編程語(yǔ)言

本文實(shí)例為大家分享了Unity3d如何通過(guò)射線使物體移動(dòng)的具體代碼,供大家參考,具體內(nèi)容如下

Unity3D實(shí)現(xiàn)射線使物體移動(dòng)

實(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)左鍵的時(shí)候創(chuàng)建一條射線
    if(Input.GetMouseButton(0))
    {
      //定義射線
      Ray m_ray;
      //保存碰撞信息
      RaycastHit m_hit;
      //創(chuàng)建一條從攝像機(jī)發(fā)出經(jīng)過(guò)屏幕上的鼠標(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);
 }
  //移動(dòng)方法
  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時(shí)直接等于目標(biāo)點(diǎn)
    else
      transform.position = target;
  }
}

以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI