Search code examples
unity-game-enginemathvectorposition

What makes this code work with the Y axis but not the X axis?


So I am making a game with a blink function and a fixed camera so of course I don't want the player to be able to leave the camera. So my solution is to not enable the player to pass the border of the camera with the blink. The thing is that it works amazingly for the Y axis, but less so for the X axis. (The transform.lossy scale is a place holder until I find an actual sprite & the magic numbers are the position at which the camera's edges are)

if ((transform.position += (Vector3)aim * slashDistance).x <= -8.9f)
{
    transform.position += (Vector3)aim * (8.9f + transform.position.x - (transform.lossyScale.x / 2));
}
else if ((transform.position += (Vector3)aim * slashDistance).x >= 8.9f)
{
    transform.position += (Vector3)aim * (8.9f - transform.position.x - (transform.lossyScale.x / 2));
}

if ((transform.position += (Vector3)aim * slashDistance).y <= -5f)
{
    transform.position += (Vector3)aim * (5f + transform.position.y - (transform.lossyScale.y / 2));
}
else if ((transform.position += (Vector3)aim * slashDistance).y >= 5f)
{
    transform.position += (Vector3)aim * (5f - transform.position.y - (transform.lossyScale.y / 2));
}

Solution

  • You have this statement in your if conditions:

    transform.position += (Vector3)aim * slashDistance
    

    This statement has a side-effect - it will move the player. Hence, you will move the player each time any of the four conditions is evaluated. Not very reasonable. So, when you move outside of the allowed x-range, the first block will move the player back inside. But then, the second block moves the player again outside of the range and the y-check will not be able to compensate this. So, simply put the effect outside of your conditions. This will also make your code much easier to read:

    transform.position += (Vector3)aim * slashDistance
    if (transform.position.x <= -8.9f)
    {
        transform.position += (Vector3)aim * (8.9f + transform.position.x - (transform.lossyScale.x / 2));
    }
    else if (transform.position.x >= 8.9f)
    {
        transform.position += (Vector3)aim * (8.9f - transform.position.x - (transform.lossyScale.x / 2));
    }
    
    if (transform.position.y <= -5f)
    {
        transform.position += (Vector3)aim * (5f + transform.position.y - (transform.lossyScale.y / 2));
    }
    else if (transform.position.y >= 5f)
    {
        transform.position += (Vector3)aim * (5f - transform.position.y - (transform.lossyScale.y / 2));
    }