如果有人看不懂下面的代码的使用方法,这里准备了一个网盘项目文件压缩包,用unity2017及以上版本打开即可
网址:https://pan.baidu.com/s/1Pu2qgNV7CqCjF613EwO3zg
using UnityEngine;
public class Control : MonoBehaviour {
public Texture Point, Ring;
public static float x, y;
Vector2 Posi, Pos0, Pos00, Pos_;
float RingW, RingH, PointW, PointH;
bool Drag;
void Start() {
Pos00 = Pos0 = Posi = new Vector2(300, 800);
RingW = RingH = 400;
PointW = PointH = 150;
Drag = false;
x = y = 0;
}
void Update() {
}
void OnGUI() {
if (Event.current.type == EventType.mouseDown) {
//是否需要移动控件
Vector2 Posq = Event.current.mousePosition;
float vz0;
vz0 = (Posq.x - Pos0.x) * (Posq.x - Pos0.x) + (Posq.y - Pos0.y) * (Posq.y - Pos0.y);
vz0 = Mathf.Sqrt(vz0);
if (vz0 < RingW / 2) {
Pos0 = Event.current.mousePosition;
Drag = true;
}
}
//抬起手指,归位
if (Event.current.type == EventType.mouseUp) {
Drag = false;
Pos0 = Pos00;
}
//拖拽
x = 0;
y = 0;
float vx = 0, vy = 0, vz;
Pos_ = Event.current.mousePosition;
vz = (Pos_.x - Pos0.x) * (Pos_.x - Pos0.x) + (Pos_.y - Pos0.y) * (Pos_.y - Pos0.y);
vz = Mathf.Sqrt(vz);
if (Drag) Posi = Pos_;
else Posi = Pos0;
if (vz > RingW / 2) {
vx = (Posi.x - Pos0.x) / vz * RingW / 2 + Pos0.x;
vy = (Posi.y - Pos0.y) / vz * RingH / 2 + Pos0.y;
Posi = new Vector2(vx, vy);
}
GUI.DrawTexture(new Rect(Posi.x - PointW / 2, Posi.y - PointH / 2, PointW, PointH), Point);
GUI.DrawTexture(new Rect(Pos0.x - RingW / 2, Pos0.y - RingH / 2, RingW, RingH), Ring);
//外部速度接口
if (Drag) Posi = Event.current.mousePosition;
else Posi = Pos0;
vz = (Posi.x - Pos0.x) * (Posi.x - Pos0.x) + (Posi.y - Pos0.y) * (Posi.y - Pos0.y);
vz = Mathf.Sqrt(vz);
x = Mathf.Abs(Posi.x - Pos0.x) / (RingW / 2) * (Posi.x - Pos0.x) / vz;
y = -Mathf.Abs(Posi.y - Pos0.y) / (RingH / 2) * (Posi.y - Pos0.y) / vz;
if (vz == 0) x = y = 0;
if (vz > RingW / 2) {
x= (Posi.x - Pos0.x) / vz;
y= -(Posi.y - Pos0.y) / vz;
}
//其它脚本获得速度方向时,可写作:
//gameObject.transform.Translate(Time.deltaTime * Speed * Control.x, Time.deltaTime * Speed * Control.y, 0);
}
}