How to move 2D Object within camera view boundary

后端 未结 4 1597
感动是毒
感动是毒 2020-12-21 23:47

I have a scene that my camera doesn\'t follow my player. When player reaches the end of camera I want player to can\'t go further (out of camera view). How can I do this?

4条回答
  •  时光说笑
    2020-12-22 00:06

    You need to limit your transform's position based on the edges of the camera. Here is an answer describing the different coordinate systems in unity

    You're probably looking to do something like this:

    float xMin = Camera.main.ViewportToWorldPoint(Vector3.zero).x;
    float xMax = Camera.main.ViewportToWorldPoint(Vector3.one).x;
    
    Vector3 currentPos = transform.position;
    float dx = Input.GetAxis ("Horizontal") / 100 * speed;
    Vector3 desiredPos = new Vector3(currentPos.x + dx, currentPos.y, currentPos.z);
    
    Vector3 realPos = desiredPos;
    
    if(desiredPos.x > xMax)
        realPos.x = xMax;
    else if(desiredPos.x < xMin)
        realPos.x = xMin;
    
    transform.position = realPos;
    

    Read up here for more info on ViewportToWorldPoint(), it's extremely useful to become comfortable with the different coordinate spaces and how you can convert between them.

提交回复
热议问题