我正在学习Unity并使用版本4.3的Evac City教程。此示例是一个自上而下的2D射击游戏,它使用鼠标旋转,键盘使用箭头或WASD键进行移动。
我尝试过的一件事并没有太多运气,那就是改变运动的方向。我希望键盘移动相对于玩家的方向而不是世界平面,这样W键会让你向前移动你的方向,S键会让你向后移动,A键会让你滑动向左,D键向右滑动。
代码的相关部分似乎是:
void FindPlayerInput()
{
// find vector to move
inputMovement = new Vector3(Input.GetAxis("Horizontal"), 0, Input.GetAxis("Vertical"));
// find vector to the mouse
tempVector2 = new Vector3(Screen.width * 0.5f, 0, Screen.height * 0.5f); // the position of the middle of the screen
tempVector = Input.mousePosition; // find the position of the moue on screen
tempVector.z = tempVector.y; // input mouse position gives us 2D coordinates, I am moving the Y coordinate to the Z coorindate in temp Vector and setting the Y coordinate to 0, so that the Vector will read the input along the X (left and right of screen) and Z (up and down screen) axis, and not the X and Y (in and out of screen) axis
tempVector.y = 0;
inputRotation = tempVector - tempVector2; // the direction we want face/aim/shoot is from the middle of the screen to where the mouse is pointing
}
void ProcessMovement()
{
tempVector = rigidbody.GetPointVelocity(transform.position) * Time.deltaTime * 1000;
rigidbody.AddForce(-tempVector.x, -tempVector.y, -tempVector.z);
rigidbody.AddForce(inputMovement.normalized * moveSpeed * Time.deltaTime);
transform.rotation = Quaternion.LookRotation(inputRotation);
transform.eulerAngles = new Vector3(0, transform.eulerAngles.y + 180, 0);
print("x:" + transform.eulerAngles.x + " y:" + transform.eulerAngles.y + " z:" + transform.eulerAngles.z);
transform.position = new Vector3(transform.position.x, 0, transform.position.z);
}
我尝试了一些不同的东西,并认识到Input.GetAxis调用来自键盘映射,但不是如何将移动重定向到播放器轴。
答案 0 :(得分:1)
你想要做的是将输入方向从玩家的本地空间转换为世界空间,将其置于有用的“空间”术语中。您可以使用Transform.TransformDirection
执行此操作:
Vector3 worldInputMovement = transform.TransformDirection(inputMovement.normalized);
rigidbody.AddForce(worldInputMovement * moveSpeed * Time.deltaTime);
这是有效的,因为TransformDirection
会旋转你给它的矢量以将其放在世界空间中,而AddForce
需要一个世界空间矢量。