Mathf.Clamp函数扭曲对象大小

时间:2017-09-26 08:17:08

标签: c# unity3d unity5 clamp

我在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 size从侧面减小。 这是Clamp功能代码,可以减小船的尺寸。

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

发货尺寸之前: enter image description here

发货后尺寸: enter image description here

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

2 个答案:

答案 0 :(得分:2)

修改Rigidbody的position确实移动了Transform,但是在最后一个物理步骤之后。虽然它被认为更快,但它可能会导致一些不良行为,因为你正在移动引擎的物理也在使用的东西,并且在FixedUpdate函数中执行它,这应该主要用于物理问题。将Player.GetComponent<Rigidbody>().position替换为Player.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)
    );
}

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

作为旁注,您应该在班级中保存对玩家变换的引用,这样您就不必每次都使用GetComponent函数。

答案 1 :(得分:0)

通过在平面下方(约-4)推动背景“四边形”并将船舶的Y值设置为0来解决问题