生活随笔
收集整理的這篇文章主要介紹了
[Unity实践笔记] 俯视视角人物360°移动脚本
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
實現效果
俯視視角下,wasd控制人物移動,人物可進行360°流暢轉身。
知識點
角度計算:繞y軸軟轉到direction方向需要轉多少度
float angle
= Vector3
.Angle(new Vector3(0, 1, 0), direction
);
?
在局部坐標系中旋轉到(0, 0 , angle)
transform
.localEulerAngles
= new Vector3(0, 0, angle
);
?
不使用transform.Rotate(vec3)的原因
Rotate(vec3)為旋轉vec3角度(相對角度),只要按鍵按下左右鍵就會執行,會達到令人凌亂的效果。
localEulerAngles(vec3)為旋轉到vec3角度(絕對角度),如果已經到達該角度,再怎么按左右鍵都不會過度旋轉。
?
代碼
掛載在玩家Object上
public class PlayerController : MonoBehaviour
{public float speed
= 1.0f;public Animator anim
;private void Start(){anim
= GetComponentInChildren<Animator>();}void FixedUpdate(){float xPosition
= Input
.GetAxis("Horizontal") * speed
;float yPosition
= Input
.GetAxis("Vertical") * speed
;if (Input
.GetKey("a")||Input
.GetKey("d")||Input
.GetKey("w")||Input
.GetKey("s")){transform
.Translate(xPosition
, yPosition
, 0);}anim
.SetFloat("speed", Mathf
.Abs(xPosition
)+Mathf
.Abs(yPosition
));}
此腳本只負責移動玩家Object,不管玩家如何旋轉。
注意:若帶有RigidBody組件,必須使用FixedUpdate(),否則會解鎖奇奇怪怪的移動方式。
?
掛載在玩家Object子物體,sprite上(帶有玩家sprite和animator)
public class SpriteSpinner : MonoBehaviour
{SpriteRenderer spriteRenderer
;Vector3 direction
;bool moveV
;bool moveH
;void Start(){spriteRenderer
= GetComponent<SpriteRenderer>();}void Update(){direction
.x
= Input
.GetAxis("Horizontal");direction
.y
= Input
.GetAxis("Vertical");if(direction
.x
== 0 && direction
.y
!= 0){moveV
= true;moveH
= false;}else if(direction
.y
== 0 && direction
.x
!= 0){moveH
= true;moveV
= false;}else{moveH
= false;moveV
= false;}if(moveV
){int rotateY
= direction
.y
> 0 ? 0 : 180;transform
.localEulerAngles
= new Vector3(0, 0, rotateY
);}else if(moveH
){int rotateX
= direction
.x
> 0 ? -90 : 90;transform
.localEulerAngles
= new Vector3(0, 0, rotateX
);}else{int signX
= direction
.x
< 0 ? 1 : -1;float angle
= signX
* Vector3
.Angle(new Vector3(0, 1, 0), direction
);if(angle
!= 0) transform
.localEulerAngles
= new Vector3(0, 0, angle
);}}
}
此腳本只負責旋轉玩家帶有sprite組件的子物體(即子物體的旋轉不會影響玩家整體的移動方向)
?
Bug & 待修改
停止控制后會自動旋轉一定角度
總結
以上是生活随笔為你收集整理的[Unity实践笔记] 俯视视角人物360°移动脚本的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。