ImageBG脚本
usingUnityEngine;
usingSystem.Collections;
usingUnityEngine.UI;
//不手动添加ScrollRect组件,让脚本继承与ScrollRect,从而获得ScrollRect的属性、方法
public class ScrollCricle:ScrollRect{
private float mRadius;
private Vector3 offsetVector3=Vector3.zero;//摇杆的偏移
protected override void Start( ){
base.Start( );
//计算摇杆移动半径
mRadius=(transform as RectTransform).sizeDelta.x*0.5f;
}
voidUpdate( ){
CalculateOffect();
}
public override void OnDrag(UnityEngine.EventSystems.PointerEventData eventData){
//获得父类属性
base.OnDrag(eventData);
base.content.anchoredPosition=Vector3.ClampMagnitude(base.content.anchoredPosition,mRadius);
}
//计算偏移
privatevoidCalculateOffect( ){
//(-1,1)~(1,1)
offsetVector3=content.localPosition/mRadius;
}
public Vector3 GetoffsetVector3( ){
return offsetVector3;
}
}
被控制物体脚本
usingUnityEngine;
usingSystem.Collections;
usingSystem.Collections.Generic;
public class CubeMove:MonoBehaviour{
public ScrollCricle scrollCricle;//获得Scroll脚本
voidStart( ){
}
voidUpdate( ){
Vector3 offset=scrollCricle.GetoffsetVector3();
//物体的朝向随着摇杆的方向移动(四元数)
transform.rotation=Quaternion.LookRotation(new Vector3(offset.x,0,offset.y));
transform.position+=newVector3(offset.x,0,offset.y)*10*Time.deltaTime;
}
}