【问题标题】:Adjust Input.GetAxis To Face Player Axis调整 Input.GetAxis 以面对玩家轴
【发布时间】:2015-09-14 22:27:35
【问题描述】:

我正在学习 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 调用来自键盘映射,而不是如何将移动重新定向到玩家轴。

【问题讨论】:

    标签: c# unity3d


    【解决方案1】:

    您要做的是将输入方向从玩家的本地空间转换到世界空间,将其置于众所周知的“空间”术语中。你可以通过Transform.TransformDirection 做到这一点:

    Vector3 worldInputMovement = transform.TransformDirection(inputMovement.normalized);
    rigidbody.AddForce(worldInputMovement * moveSpeed * Time.deltaTime);
    

    这是因为TransformDirection 会旋转你给它的向量以将其放入世界空间,而AddForce 需要一个世界空间向量。

    【讨论】:

    • 谢谢。这对我的球员运动有效。它对敌人的运动有一些副作用,我仍然需要克服这些副作用,但让我朝着正确的方向前进(可以这么说......)。
    • 奇怪的是它会影响敌人的移动,但我想我没有完整的上下文。也许在设置输入时进行转换而不是在应用输入时进行转换:即在inputMovement = new Vector3(Input.GetAxis("Horizontal"), ...,因为我假设它不是共享的,但ProcessMovement 是。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-11
    • 1970-01-01
    • 1970-01-01
    • 2022-11-22
    • 1970-01-01
    相关资源
    最近更新 更多