Unity 鼠标拖动场景内的物体

本文介绍了一个Unity脚本,用于实现鼠标拖动场景中物体的功能。通过OnMouseEnter和OnMouseExit方法改变物体大小,OnMouseOver使物体旋转,OnMouseDrag则处理物体的拖动。moveObject和moveObject_fixdepth两个方法分别处理物体的拖动,后者考虑了物体深度,确保拖动时始终在相机前。
摘要由CSDN通过智能技术生成
using UnityEngine;
using System.Collections;

public class mouse_Drag : MonoBehaviour {

    public Camera mCamera;
    public float deth = 10f;
    //鼠标放到物体上
    void OnMouseEnter()
    {
        this.transform.localScale = new Vector3(1.3f,1.3f,1.3f);
    }

    //鼠标在物体上移除的时候
    void OnMouseExit()
    {
        this.transform.localScale = new Vector3(1.0f, 1.0f, 1.0f);
    }
    //鼠标放在物体上一直触发
    void OnMouseOver()
    {
        this.transform.Rotate(Vector3.up,45 * Time.deltaTime,Space.Self);
    }

    void OnMouseDrag()
    {
        //moveObject();
        moveObject_fixdepth();
    }

    void moveObject()
    {
        //把鼠标点坐标转换为世界坐标,并发出一条射线
        Ray r = mCamera.ScreenPointToRay(Input.mousePosition);
        //采集射线打到的物体信息
        RaycastHit hit;
        //设置射线长度为1000
        if(Physics.Raycast(r,out hit, 1000f,1))
        {
            this.transform.position = new Vector3(hit.point.x,hit.point.y,hit.point.z);
            Debug.DrawLine(r.origin,hit.point,Color.red);
        }

    }

    void moveObject_fixdepth()
    {
        Vector3 mouseScreen = Input.mousePosition;
        mouseScreen.z = deth;
        Vector3 mouseWorld = mCamera.ScreenToWorldPoint(mouseScreen);
        this.transform.position = mouseWorld;
    }


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值