0

我正在 Unity 中制作 SpaceShooter 游戏。

这是功能。

 void FixedUpdate ()
{

    float moveHorizontal = Input.GetAxis ("Horizontal");
    float moveVertical = Input.GetAxis ("Vertical");


    Vector3 movement = new Vector3 (moveHorizontal, 0.0f, moveVertical);
    Player.GetComponent<Rigidbody>().velocity=movement*speed;

    Player.GetComponent<Rigidbody> ().rotation = Quaternion.Euler(0.0f,0.0f,Player.GetComponent<Rigidbody> ().velocity.x * -tilt);
}

在上面的代码中,当我添加 Clamp 函数以将 Ship 限制在边界内时,Ship 的大小从侧面减小。这是减小船体尺寸的夹紧功能代码。

 Player.GetComponent<Rigidbody> ().position=new Vector3 
    (
        Mathf.Clamp(Player.GetComponent<Rigidbody>().position.x, boundary.xMin, boundary.xMax),
        0.0f,
        Mathf.Clamp(Player.GetComponent<Rigidbody>().position.z, boundary.zMin, boundary.zMax)
    );

船舶尺寸 之前: 在此处输入图像描述

船舶尺寸 之后: 在此处输入图像描述

我已经在 Clamping 函数中准确地给出了屏幕边界值。

4

2 回答 2

2

修改刚体的位置确实会移动变换,但在最后一个物理步骤之后。虽然它被认为更快,但它可能会导致一些不希望的行为,因为您正在移动引擎的物理也在使用的东西,并且在FixedUpdate应该主要用于物理问题的函数中执行它。替换Player.GetComponent<Rigidbody>().positionPlayer.GetComponent<Transform>().position。此外,由于您在这里没有使用任何物理,而是直接修改对象位置,因此请在Update函数中设置这部分代码。

void Update()
{
    Transform playerTransform = Player.GetComponent<Transform>();

    playerTransform.position=new Vector3 
    (
        Mathf.Clamp(playerTransform.position.x, boundary.xMin, boundary.xMax),
        0.0f,
        Mathf.Clamp(playerTransform.position.z, boundary.zMin, boundary.zMax)
    );
}

如果您想使用刚体移动对象,请不要这样做。请考虑改用MovePosition函数。以您所做的方式移动它会导致它传送而不是在同一帧上计算碰撞,而是在下一帧上计算。

作为旁注,您应该在您的类中保存对播放器转换的引用,因此您不必GetComponent每次都使用该函数。

于 2017-09-26T08:23:50.663 回答
0

通过将背景“quad”推到飞机下方(大约 -4)并将船的 Y 值设置为 0 解决了这个问题

于 2017-09-26T12:51:42.910 回答