一、U3D中继承就是子类和父类之间的继承关系。
这里我们的父类为RoteBtn.cs
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
public class RoteBtn : MonoBehaviour,IDragHandler {
public static RoteBtn instance;
public Transform target;
float speed = .3f;
void Awake(){
RoteBtn.instance = this;
}
public void OnDrag(PointerEventData eventData){
// Vector3 Vec3rote = new Vector3 (eventData.delta.y, -eventData.delta.x);
Vector3 Vec3rote = new Vector3 (0, -eventData.delta.x);
// target.Rotate (Vec3rote * speed, Space.World);
target.Rotate (Vec3rote * speed, Space.Self);
}
}
这里的子类为RotateBtnChild.cs,子类继承时直接在父类位置输入正确的父类名称即可
public class RotateBtnChild : RoteBtn{}
二、射线的使用
相当于从摄像机的某点射出射线,射出距离最大为5000.这里我们使用鼠标左键点击时响应处理射线。继承IPointerDownHandler,因此需要重载其函数OnPointerDown(PointerEventData eventData){}。即鼠标在屏幕点击时,确定射线是否与物体碰撞。如果碰撞,则可根据碰撞物体的名称进行旋转操作。以下是代码。
public class RotateBtnChild : RoteBtn,IPointerDownHandler {
public void OnPointerDown (PointerEventData eventData){
Ray ray = Camera.main.ScreenPointToRay (eventData.position);
RaycastHit hit;
if(Physics.Raycast(ray,out hit,5000)){//5000为射线最大有效值
if(hit.collider!=null){
if(hit.transform.name=="Cube_red" || hit.transform.name=="Cube_blue"){
print (hit.transform.name+"dsfdsf");
base.target = hit.transform;
}
}
}
}
}
三、屏幕显示碰撞物体名称
使用Text UI工具进行显示,代码如下。
Text myText;
// Use this for initialization
void Start () {
myText = this.GetComponent<Text> ();
}
// Update is called once per frame
void Update () {
myText.text = "当前目标为"+RoteBtn.instance.target.name;
}
利用上面的方法,实现多模型识别时,鼠标分别点击不同的模型,即选中该模型,左右拖拽旋转该模型。模型之间的旋转各自独立,不相互影响。