freezing the y position of the camera in unity3d

时间:2017-08-05 11:11:45

标签: c# android unity3d camera

I am making a plat former game and I'm having a problem in the camera position of the game im imitating the camera movement of the 1st version of the super mario bros but every time I move my character the camera will go up until the character will disappear. How can I fix it?

public Transform playerPos;
public Transform rigthCamBoundary;
public Transform levelEnd;

Vector3 destination;
Vector3 velocity = Vector3.zero;

private void Start()
{
    destination = Vector3.ClampMagnitude(levelEnd.position, 22.8f);
    destination = new Vector3(destination.x, destination.y, 13.5f);
}

private void FixedUpdate()
{
    if (Vector3.Distance(playerPos.position, rigthCamBoundary.position) < 13.7f)
        transform.position = Vector3.SmoothDamp(transform.position, levelEnd.position, ref velocity, .14f, 8.5f);
}

1 个答案:

答案 0 :(得分:1)

To freeze the y-axis, get the y-axis value when the game runs. After using Vector3.SmoothDamp, change the y-axis to that variable you got before then apply it to your transform.

public Transform playerPos;
public Transform rigthCamBoundary;
public Transform levelEnd;

Vector3 destination;
Vector3 velocity = Vector3.zero;
float yPos;

private void Start()
{
    destination = Vector3.ClampMagnitude(levelEnd.position, 22.8f);
    destination = new Vector3(destination.x, destination.y, 13.5f);

    //Get the default camera y pos
    yPos = transform.position.y;
}

private void FixedUpdate()
{
    if (Vector3.Distance(playerPos.position, rigthCamBoundary.position) < 13.7f)
    {
        Vector3 tempPos = Vector3.SmoothDamp(transform.position, levelEnd.position, ref velocity, .14f, 8.5f);

        //Apply the default camera y pos
        tempPos.y = yPos;
        transform.position = tempPos;
    }
}

Note that I don't know if this code is attached to the camera but this answer assumes it is. Otherwise the solution still remains the-same but you just have to change transform.position.y and transform.position to something else.