【Unity3D日常开发】Unity3D中实现画板效果_物体跟随鼠标移动
【Unity3D日常开发】Unity3D中实现画板效果_物体跟随鼠标移动_02


using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class player : MonoBehaviour
{
public GameObject PrintPrefab;
// Use this for initialization
void Start()
{

}

// Update is called once per frame
void Update()
{
//Debug.Log(Camera.main.ScreenToWorldPoint(Input.mousePosition)+new Vector3(0,0,10));

Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition) + new Vector3(0, 0, 10);

transform.position = mousePos;
if (Input.GetMouseButton(0))
{
Instantiate(PrintPrefab, transform.position, transform.rotation);
}
}
}

代码解析:

1.屏幕坐标转化为三维坐标

Vector3 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition) + new Vector3(0, 0, 10);

2.物体跟随鼠标移动

transform.position = mousePos;

3.创建预制体

if (Input.GetMouseButton(0))
{
      Instantiate(PrintPrefab, transform.position, transform.rotation);
}

【Unity3D日常开发】Unity3D中实现画板效果_物体跟随鼠标移动_03

把脚本给一个空物体就行。空物体的坐标为(0,0,0),旋转坐标为(0,0,0)