一、简单的场景
二、鼠标移向物体、选中、点击、移动、离开。
1、鼠标移向物体
2、鼠标选中物体
首先移向物体
然后选中物体。
3.移动物体
三、下面是程序代码
脚本:ApiOnMouseButton
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Reflection;
public class ApiOnMouseButton : MonoBehaviour {
public Renderer rend;
public Vector3 targetPos;
public Vector3 lastPos;
bool isdrag=false;//用来判断物体是否被拖拽
void Start () {
rend = GetComponent<Renderer> ();
}
void Update () {
}
//当鼠标移动到物体上
void OnMouseEnter() {
if(!isdrag)
rend.material.color = Color.blue;
}
//当鼠标按下物体
void OnMouseDown(){
if(!isdrag){
rend.material.color = Color.yellow ;
lastPos = Camera.main.ScreenToViewportPoint( Input.mousePosition)-Camera.main.WorldToViewportPoint(transform.position);
}
}
//当鼠标拖拽物体
void OnMouseDrag(){
targetPos = Camera.main.ViewportToWorldPoint( Camera.main.ScreenToViewportPoint(Input.mousePosition)-lastPos);
transform.position = new Vector3 (targetPos.x, targetPos.y, targetPos.z);
isdrag = true;
}
//当鼠标离开物体
void OnMouseExit(){
if(!isdrag)
rend.material.color = Color.white;
}
void OnMouseUp(){
rend.material.color = Color.blue;
isdrag = false;
}
}
将脚本ApiOnMouseButton拖拽到物体身上即可运行~
网友评论