Trying to make my spirte stay inbound camera view

Hello there, I’m very new to programming and also Unity. I’m a artist who is trying to develop the passion of creating games as a hobby.
So I’m trying to create my first project wich it’ll be a Infinite Runner, but I’m already struggling with a bit of code. I’m trying to keep my sprite within the boundaries of my camera, until now I can move it up and down, but it goes off the camera bounds. I tried to wrap my mind around Clamp method, but did’nt get it to work properly. Please help.

So I guess I have to discover the my viewport height and width and clamp my movement to these values, but I don’t know how to do it with code. Is this thinking right?

This is how my code is looking right now.

First, welcome to the unity forum :slight_smile:

Second, limiting character movement which is driven by the physics system should be done through the physics system to avoid simulation glitches (meaning: don’t change your transform.position directly). Clamping the transform position is possible but I would advise against it.

There are two possible scenarios which you could have.
A) Your camera is following the character and you want to keep the char visible at all times, especially at high velocities. I assume that’s not your problem (yet).

B) You want to limit the size of your level to the camera bounds. I think that’s more what you want at the moment.

So, to limit the movement of a physics object you can use colliders or apply a counter force with MoveTo (tricky). You can start by placing 2D box colliders at the edges. Don’t forget to make them collide with your character. The exact position of these colliders can be determined via scripting using Camera.ScreenToWorldPoint (notice the Z value is the distance of your plane to the camera). What you would do is use ScreenToWorldPoint to calculate the top, bottom, left and right position limits in the world and then move the colliders there or call MoveTo is the char is outside.

Happy Coding!

Hey @_geo1 thanks for the quick answer. I thought about what you said on using physics for movement.
So i decided to give it a try with presskeydown method to try to simplify it. I was able to limit the movement, but the sprite still goes offscreen a bit, I guess the code takes the center of the sprite as a reference and that’s why it’s going halfway off the camera.
I actually have no idea if I’m doing this right or how I can fix this, what do you think? I tried using to get the size of my sprite and subtract from the screen.height, but didn’t work. I guess I don’t know how to use it properly.

So this is how it’s looking right now.

public class Teste : MonoBehaviour
{

    private Vector2 playerPos;
    public float speed;
    private Vector3 cameraHeight;
    public float smooth;
    private SpriteRenderer sprite;
   
    // Start is called before the first frame update
    void Start()
    {

        sprite = GetComponent<SpriteRenderer>();
       

    }

    // Update is called once per frame
    void Update()
    {
        Debug.Log(sprite.bounds.size.y);

        cameraHeight = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, 0.0f));
        transform.position = Vector2.MoveTowards(transform.position, playerPos, smooth * Time.deltaTime);

        // here I tried to subtract the cameraHeight and sprite, but I don't know how to extract the value from the sprite variable
        if (Input.GetKeyDown (KeyCode.UpArrow) && playerPos.y <= cameraHeight.y)
            {
            playerPos = new Vector2(transform.position.x, transform.position.y + speed);
        }

        if (Input.GetKeyDown(KeyCode.DownArrow) && playerPos.y >= cameraHeight.y * -1)
        {
            playerPos = new Vector2(transform.position.x, transform.position.y - speed);
        }

    }
}

Physics isn’t the answer if you’re directly driving the Transform. You should never modify the Transform when using 2D Physics. If it moves in physics then move the Rigidbody2D using its API.

Using a collider like an EdgeCollider2D to set edges that align with the edges of the screen view will work fine just as it’ll work for any other type of collision. It’ll not work if you don’t configure it correctly obviously.

There’s no right and wrong way here. If you want to use physics for your character for anything else then it makes sense to use physics but if not, then stick to just clamping your player position in script and driving the Transform.