C#鼠标点击物体,并带着物体移动
通过射线检测进行控制
using UnityEngine;
using System.Collections;
///
/// 鼠标点击物体并且控制移动
///
public class Move : MonoBehaviour {
// Use this for initialization
bool isOk = false; //初始值false
void Start()
{
//获取MeshRenderer的材质球并变为红色
this.GetComponent<MeshRenderer>().material.color = Color.red;
}
// Update is called once per frame
void Update()
{
//判断是否按下左键
if (Input.GetMouseButtonDown(0))
{
//发射线
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
//我要移动的物体名字叫Sphere
if (hit.transform.name == "Sphere")
{
isOk = true;
}
}
}
//抬起左键 isok为假
if (Input.GetMouseButtonUp(0))
{
isOk = false;
}
//isok为真,移动物体
if (isOk)
{
//获取需要移动物体的屏幕坐标
Vector3 targer = Camera.main.WorldToScreenPoint(this.transform.position);
//获取鼠标的屏幕坐标,,将物体的屏幕坐标的z轴赋给鼠标坐标
Vector3 mouse = Input.mousePosition;
mouse.z = targer.z;
//将鼠标的屏幕坐标转变成世界坐标
Vector3 mouseScreenPos = Camera.main.ScreenToWorldPoint(mouse);
//移动的物体的位置就等于转换成世界坐标的鼠标位置
this.transform.position = mouseScreenPos;
}
}
}
欢迎留言关注