基本原理:通過Input.GetTouch().position,獲得觸摸位置并根據手指移動方向來計算出技能釋放方向,然后通過LIneRenderer生成方向指示線,實現類似于《王者榮耀》指向性技能釋放時的方向指示效果。
void Update(){
//假設觸摸點1正在用于控制角色方向;觸摸點2位于屏幕右側,該側有技能按鈕;
if (Input.touchCount>0 && Input.GetTouch(1).position.x > Screen.width/2) {
//觸摸點2被觸碰
if (Input.GetTouch(1).phase == TouchPhase.Began)
{
//獲得第二個觸摸點的位置,并保存,將用作計算相對位置的基點
m_DragStartPoint = Input.GetTouch(1).position;
}
// 觸摸點2在移動
if (Input.GetTouch(1).phase == TouchPhase.Moved)
{
// 根據觸摸點2的位置,計算需要的方向向量;
CalDir(Input.GetTouch(1).position);
// 計算全局坐標系下的Z方向至上一步得到的方向向量的夾角;
m_rotAngle = AngleBetweenVector3(Vector3.forward, m_TouchDeltaDir);
// 調用LineRenderer繪制線段
DrawLine (m_LineStartPosition.position,m_LineEnd);
// 根據該夾角,計算技能釋放時所需的旋轉Quanternion
m_SpellRotation = Quaternion.Euler(0,m_rotAngle,0);
//觸摸點2保持靜止
}else if(Input.GetTouch(1).phase == TouchPhase.Stationary){
// 這一步原理同上,用于確保角色移動時線段的起點能夠與角色同步
CalDir(Input.GetTouch(1).position);
DrawLine (m_LineStartPosition.position,m_LineEnd);
//觸摸點2終止,手指離開屏幕
}else if(Input.GetTouch(1).phase == TouchPhase.Ended){
// 這里調用你的技能,實現技能釋放;
// 由于這里用了ParitcleSystem作為被釋放的技能,對應的transform在初始化時無Rotation,也就是transform.forward與Vector3.forward一致,因此,在釋放技能時,需要將之前得到的Quanterniou作為參數,在ParticleSystem生成時便旋轉至與方向指示線一致的方向。
m_Spell.SpellCast (1,m_SpellRotation,0);
//停止線段繪制;
DropLine();
}
//DrawLine (m_LineStartPosition.position,m_LineEnd);
}
}
void CalDir(Vector2 touchposition){
// 計算自初始觸摸位置至當前觸摸位置的向量
m_TouchDeltaPosition = touchposition - m_DragStartPoint;
// 注意: Input.Touch().Position 得到的是Vector2;
// 將Vector2 轉化為Vector3,由于是在X-Z平面繪制,所以Y方向為0;
m_TouchDeltaDir = new Vector3(m_TouchDeltaPosition.x, 0, m_TouchDeltaPosition.y);
// 上一步得到一個在全局坐標系下,觸摸位置相對于基點的方向向量;
// 接下來便可以利用這個方向向量,從角色的位置畫出一條直線作為技能釋放方向的指示。
// 計算直線的繪制終點
m_LineEnd = m_LineStartPosition.position + m_TouchDeltaDir.normalized * 10f;
}
float AngleBetweenVector3(Vector3 vec1, Vector3 vec2){
float sign = (vec2.x < vec1.x) ? -1.0f : 1.0f;
return (Vector3.Angle (vec1,vec2) ) * sign;
}
void DrawLine(Vector3 start,Vector3 end){
if (!GetComponent<LineRenderer> ()) {
m_LineRenderer = gameObject.AddComponent<LineRenderer> ();
}
m_LineRenderer.enabled = true;
m_LineRenderer.startColor = Color.red;
m_LineRenderer.endColor = Color.red;
m_LineRenderer.startWidth = 0.2f;
m_LineRenderer.endWidth = 0.2f;
m_LineRenderer.SetPosition (0,start);
m_LineRenderer.SetPosition (1,end);
}
void DropLine(){
if (!GetComponent<LineRenderer> ()) {
return;
} else {
m_LineRenderer.enabled = false;
}
}
//m_Spell.SpellCast
public void SpellCast(...){
...
// m_Spell 對應所釋放的技能,是一個以ParticleSystem為基礎的特效;
// SpellCastPosition 是技能釋放位置,也就是ParticleSystem開始的位置;
// m_SpellRotation 是ParticleSystem的旋轉量;
GameObject spell = (GameObject)Instantiate (m_Spell, SpellCastPosition, m_SpellRotation);
...
}
做完之后的效果就是下面這個樣子,這條線雖然看起來很丑,但是用來瞄準還是很實用的。
技能方向 (1).gif