根据旋转使精灵移动

时间:2014-10-26 22:48:49

标签: unity3d rotation unityscript

我是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);

}
}

2 个答案:

答案 0 :(得分:4)

你可以简单地使用它:

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

答案 1 :(得分:1)

我在寻找的是:

rigidbody2D.AddForce(transform.up); 

不是自己做所有的角度计算(这是非常错误的),而是根据你的精灵所面对的方向找到移动方向。

但也要放在这里,我的精灵在角度/ rotation.z = 0时,我的精灵正在向着计算机屏幕的顶部向上看。如果你的初始精灵看起来不是UP以外的其他地方那么你将不得不调整transform.up - &gt; -transform.right,transform.right或-transform.up以获得正确的结果。