簡體   English   中英

Unity 3D-旋轉游戲物體而不旋轉軸

[英]Unity 3D - rotating gameobject without rotating axis

希望我的標題概括了我的問題。 我在2D游戲中有一枚火箭,它只能在屏幕上水平移動。 我希望它朝着玩家的手指(移動的方向)旋轉,但無法找到一種方法來旋轉對象,而又不旋轉它所沿的整個軸線。 我只是希望它看起來已經變了,但它應該一直沿x移動。 我該怎么辦?

void Start () {
    //scoreT = GetComponent<TextMeshProUGUI> ();
    gameSpeed = 1;
    score = 0;
    Rigidbody2D rb2d = GetComponent<Rigidbody2D> ();
}

// Update is called once per frame
void Update () {
    float MoveHorizontal = Input.GetAxis ("Horizontal");
    Vector2 Movement = new Vector2 (MoveHorizontal, 0.0f);

    rb2d.rotation = Quaternion.Euler (0.0f, 0, 0f, rb2d.velocity.x * -tilt);
    transform.Translate (MoveHorizontal * speed, 0, 0);

您可以做的一件事就是修改“ rigidbody.rotation 。旋轉火箭使其旋轉,使其向一個方向或另一個方向傾斜。 例如:

float tilt - 0.3f;
//In case you prefer the rotation in another axis you just need to modify the position of the rigidbody.velocity.x * -tilt
rigidbody.rotation = Quaternion.Euler (0.0f, 0.0f, rigidbody.velocity.x * -tilt);

由於您沒有添加任何代碼,所以我不確定您如何移動火箭,因此我將發布一個通用代碼,您需要根據自己的項目進行調整:

public class PlayerController : MonoBehaviour
{
    public float speed;
    //The tild factor
    public float tilt;
    //The limit within the spaceship can move
    public Boundary boundary;

    void FixedUpdate ()
    {
        //You will need to capture the screen touchs of the user for the inputs
        float moveHorizontal = Input.GetAxis ("Horizontal");
        float moveVertical = Input.GetAxis ("Vertical");

        //Applying the movement to the GameObject
        Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
        rigidbody.velocity = movement * speed;

        //To ensure the GameObject doesnt move outside of the game boundary
        rigidbody.position = new Vector3 
        (
            Mathf.Clamp (rigidbody.position.x, boundary.xMin, boundary.xMax), 
            0.0f, 
            Mathf.Clamp (rigidbody.position.z, boundary.zMin, boundary.zMax)
        );

        //Here is where you apply the rotation 
        rigidbody.rotation = Quaternion.Euler (0.0f, 0.0f, rigidbody.velocity.x * -tilt);
    }
}

順便說一句,您正在做一個太空2D游戲,您可能會對檢查本教程感興趣:

https://unity3d.com/learn/tutorials/s/space-shooter-tutorial

您想要的是在全局/世界空間中移動對象。 看來您的火箭的移動目前正在本地空間內進行。 因此,當您旋轉火箭時,其本地坐標也會旋轉。 世界空間坐標是固定的,永遠不會在您更換火箭時旋轉。 是另一種解釋。

您還可以查看Transform.localPositionTransform.position並查看火箭在使用一個或另一個時的行為。

您可以將子畫面/渲染器作為火箭的GameObject的子代。 然后,您可以自由旋轉精靈/渲染器,而無需更改移動父級GameObject的旋轉。

這是一個駭人聽聞的解決方案,但可以達到預期的效果。

您必須相對於世界移動對象並在本地旋轉。 因此,請使用Transform.position移動對象,並使用Transform.LocalRotation旋轉對象。

或者,您可以將必須​​旋轉的零件作為平移對象的子項,然后旋轉這些子項。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM