Unity3d realizes 3D object following mouse

Time:2021-5-13

In this paper, we share the specific code of unity3d to realize 3D object following mouse for your reference. The specific content is as follows

design sketch:

1. Create a 3D object cylinder target

2. Create a glossary yellow shader

3. Mount the shader to the target object

4. Create the script mousemove.cs

Mousemove.cs code

using UnityEngine;
/*
 Let the object follow the mouse completely
  */
public class MouseMove : MonoBehaviour
{
 [header (main camera)]
 [tool tip (main camera)]
 /// <summary>
 ///Main camera
 /// </summary>
 public Camera m_mainCamera;
 [header (target object)]
 [tool tip (target object)]
 /// <summary>
 ///Target object
 /// </summary>
 public Transform m_target;
 
 void Start()
 {
  isDown = false;
  targetWTSP = m_mainCamera.WorldToScreenPoint(m_target.position);
 }
 /// <summary>
 ///Press or not
 /// </summary>
 private bool isDown;
 /// <summary>
 ///Record the position WTSP = = worldtoscreen point when the target world coordinates are converted to screen coordinates during initialization
 /// </summary>
 private Vector3 targetWTSP;
 void Update()
 {
  if (Input.GetMouseButtonDown(0)) {
   isDown = true;
  }
  if (Input.GetMouseButtonUp(0))
  {
   isDown = false;
  }
 }
 private void LateUpdate()
 {
  if (isDown)
  {
   Vector3 mouseVec3 = m_mainCamera.ScreenToWorldPoint(
    new Vector3(Input.mousePosition.x, Input.mousePosition.y, targetWTSP.z)
   );
   m_target.position = mouseVec3;
  }
 }
}

5. Create a new empty object script, mount the mousemove.cs script, and then drag the camera and target object onto the script

complete!

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

Looking for frustration 1.0

I believe you have a basic understanding of trust in yesterday’s article. Today we will give a complete introduction to trust. Why choose rust It’s a language that gives everyone the ability to build reliable and efficient software. You can’t write unsafe code here (unsafe block is not in the scope of discussion). Most of […]