[英]Rotate GameObject on Z axis while moving forward
目前,我有以下代碼,並且100%適用於3D游戲,但是我無法使其適用於2D游戲。
它應該做的是,一旦對象到達航路點,就應該朝新的航路點旋轉。 實際上發生的是它繞x
和y
軸而不是z軸旋轉。 如何使其僅在z
軸上旋轉? 根據旋轉速度,對象在向前移動時應該旋轉。 除非轉彎速度很高,否則不應立即轉彎。 但是無論如何,我還是問我如何才能只在z
軸上旋轉此代碼?
void Update () {
if(toWaypoint > -1){
Vector3 targetDir = wayPoints[toWaypoint].position - transform.position;
Vector3 newDir = Vector3.RotateTowards(transform.forward, targetDir, turnSpeed * Time.deltaTime, 0.0f);
transform.rotation = Quaternion.LookRotation(newDir);
}
if(!usePhysics && toWaypoint != -1){
transform.Translate(Vector3.forward * Time.deltaTime * speed);
next();
}
}
由於前向軸不同,外觀旋轉對於2D游戲並不可靠。 一種解決方法是,將精靈與z軸(藍色箭頭)指向精靈旋轉方向的空GameObject關聯。
看起來您正在使用Unity3D,這讓我想知道如果以2D編輯模式制作游戲,為什么首先要弄亂Z軸。 在該模式下,Z軸實際上不執行任何操作,除非您將兩個軸設置為以某種方式包含它。 我的建議是,如果尚未切換到2D編輯,請使用Vector2
代替Vector3
。
另外,嘗試將其他軸之一用作旋轉軸( transform.right
或.up
而不是.forward
)。
我找到了想要的東西:
void Update () {
if(toWaypoint > -1){
Vector3 vectorToTarget = wayPoints[toWaypoint].position - transform.position;
float angle = Mathf.Atan2(vectorToTarget.y, vectorToTarget.x) * Mathf.Rad2Deg;
Quaternion q = Quaternion.AngleAxis(angle, Vector3.forward);
transform.rotation = Quaternion.Slerp(transform.rotation, q, Time.deltaTime * turnSpeed);
}
if(!usePhysics && toWaypoint != -1){
transform.Translate(Vector3.right * Time.deltaTime * speed);
next();
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.