一池摧、簡(jiǎn)單的場(chǎng)景
二焦除、鼠標(biāo)移向物體、選中作彤、點(diǎn)擊膘魄、移動(dòng)、離開(kāi)竭讳。
1创葡、鼠標(biāo)移向物體
2、鼠標(biāo)選中物體
首先移向物體
然后選中物體绢慢。
3.移動(dòng)物體
三灿渴、下面是程序代碼
腳本: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;//用來(lái)判斷物體是否被拖拽
void Start () {
rend = GetComponent<Renderer> ();
}
void Update () {
}
//當(dāng)鼠標(biāo)移動(dòng)到物體上
void OnMouseEnter() {
if(!isdrag)
rend.material.color = Color.blue;
}
//當(dāng)鼠標(biāo)按下物體
void OnMouseDown(){
if(!isdrag){
rend.material.color = Color.yellow ;
lastPos = Camera.main.ScreenToViewportPoint( Input.mousePosition)-Camera.main.WorldToViewportPoint(transform.position);
}
}
//當(dāng)鼠標(biāo)拖拽物體
void OnMouseDrag(){
targetPos = Camera.main.ViewportToWorldPoint( Camera.main.ScreenToViewportPoint(Input.mousePosition)-lastPos);
transform.position = new Vector3 (targetPos.x, targetPos.y, targetPos.z);
isdrag = true;
}
//當(dāng)鼠標(biāo)離開(kāi)物體
void OnMouseExit(){
if(!isdrag)
rend.material.color = Color.white;
}
void OnMouseUp(){
rend.material.color = Color.blue;
isdrag = false;
}
}
將腳本ApiOnMouseButton拖拽到物體身上即可運(yùn)行~