Unity3d makes objects move with rays


In this paper, we share the specific code of how unity3d makes objects move through rays for your reference. The specific content is as follows


using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class RayTest : MonoBehaviour {
  //Set the target point of the ray on the plane
  private Vector3 target;
 // Use this for initialization
 void Start () {
    //The initialization target point coincides with its own point
    target = transform.position;
 // Update is called once per frame
 void Update () {
    //Create a ray when you click the left mouse button
      //Defining rays
      Ray m_ray;
      //Save collision information
      RaycastHit m_hit;
      //Create a ray from the camera that passes through a mouse point on the screen
      m_ray = Camera.main.ScreenPointToRay(Input.mousePosition);
      //Judge whether the ray collides with the object
      if(Physics.Raycast(m_ray,out m_hit))
        //Judge whether the collision is plane or not
          //Set the target point target to M_ Hit. Point, // and make the object on the plane, so the Y axis is 0.5f
          target = new Vector3(m_hit.point.x, 0.5f, m_hit.point.z);
  //Mobile method
  void Move(Vector3 target)
    if (Vector3.Distance(transform.position, target) > 0.1f)
      transform.position = Vector3.Lerp(transform.position, target,Time.deltaTime);
    //If the distance between the position of the object and the position of the target point is less than 0.1, it is directly equal to the target point
      transform.position = target;

The above is the whole content of this article, I hope to help you learn, and I hope you can support developer more.

Recommended Today

Angular4 actual combat (4) ngrx

ngrx Ngrx is the state management library of angular, which is the same as react Redux and is extended from redux. The example of this demonstration is to control the global loading animation display of HTTP request service through the state management of ngrx. As follows: Ngrx address:https://github.com/ngrx Ngrx mainly has four modules, which arengrx/store, […]