【问题标题】:Making a sprite move based on its rotation根据旋转使精灵移动
【发布时间】:2014-10-26 22:48:49
【问题描述】:

我是 Unity2D 的新手,我正试图让我的精灵根据它所面对的方向移动。我可以通过按 A 或 D 键来获得旋转,但是当根据我的精灵面向的方向向前移动时,我遇到了错误

我当前的代码:

#pragma strict

var moveForward : KeyCode;
var turnRight : KeyCode;
var turnLeft : KeyCode;
var fire : KeyCode;

var speed : float = 4;
var turnSpeed : float = 2;

function Update () {

// When the user wants to jet pulse forward.
if(Input.GetKey(moveForward)){

    // NEEDS FIXING HERE!!! <<<<<
    rigidbody2D.velocity.x = Mathf.Cos(rigidbody2D.rotation) * speed;
    rigidbody2D.velocity.y = Mathf.Sin(rigidbody2D.rotation) * speed;

}

// When we rotate the sprite.
if(Input.GetKey(turnRight)){

    transform.Rotate(0.0f, 0.0f, -5.0f);

}else if(Input.GetKey(turnLeft)){

    transform.Rotate(0.0f, 0.0f, 5.0f);

}
}

【问题讨论】:

    标签: unity3d rotation unityscript


    【解决方案1】:

    你可以简单地使用这个:

    rigidbody2D.velocity = (Vector2)transform.TransformDirection(Vector3.up) * speed;
    

    【讨论】:

    • 感谢您的意见,因为它帮助我得出结论:)。
    • 没问题。我说“可能”是因为我认为这取决于您的 GameObject 设置。在非常简单的测试场景中,我的代码似乎运行良好。顺便说一句,您可以将自己的答案标记为正确答案,这样每个人都知道您已经找到了答案。
    • 为了检查我自己的答案,它告诉我直到明天我才能做到,哈哈。
    【解决方案2】:

    我要找的是这个:

    rigidbody2D.AddForce(transform.up); 
    

    与其自己做所有的角度计算(这很麻烦),这只是在根据你的精灵面对的方向移动时找到。

    但也放在这里,我的 sprite 在 angle/rotation.z = 0 时是当我的 sprite 从字面上看向计算机屏幕的顶部时。如果您的初始精灵在 UP 以外的其他地方寻找,那么您必须调整 transform.up -> -transform.right、transform.right 或 -transform.up 以获得正确的结果。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-25
      • 1970-01-01
      • 2019-03-24
      相关资源
      最近更新 更多