Unity 3D - 没有旋转轴的旋转游戏对象

Unity 3D - rotating gameobject without rotating axis

希望我的标题概括了我的问题。我在 2d 游戏中有一个火箭,它只能在屏幕上水平移动。我希望它朝着玩家的手指(移动方向)旋转,但是找不到不旋转它移动的整个轴的情况下旋转 object 的方法。我只需要它看起来像是已经转动了,但它应该继续沿着 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);

您想要的是将对象移动到 global/world space。因为看起来你的火箭的运动目前正在本地 space 内发生。所以当你旋转火箭时,它的局部坐标也会旋转。世界 space 坐标是固定的,当你更换火箭时永远不会旋转。 Here 是另一种解释。

您还可以查看 Transform.localPosition and Transform.position 并了解您的火箭在使用其中一种时的表现。

您必须相对于世界移动对象并在本地旋转。 因此,使用 Transform.position 移动您的对象并使用 Transform.LocalRotation 旋转它。

或者您可以将必须​​旋转的部分作为平移对象的子对象,然后旋转子对象。

您可以将 sprite/renderer 作为您的火箭游戏对象的子对象。 然后你可以自由旋转 sprite/renderer 而不改变你移动父游戏对象的旋转。

这是一个 hacky 解决方案,但它达到了预期的结果。

您可以做的一件事是修改 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);

由于您没有添加任何代码,我不确定您是如何移动火箭的,所以我将post一个通用代码,您需要根据自己的项目进行调整:

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);
    }
}

顺便说一句,您正在制作 space 2D 游戏,您可能有兴趣查看本教程:

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