[2D platformer] Placing camera between player and mouse
Hello! In my 2D game camera follows the cursor, and player stays visible. Here is my script:
Vector3 position = (target.position + camera.ScreenToWorldPoint(Input.mousePosition)) / 2f;
Vector3 destination = new Vector3(position.x, position.y, -10);
transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, dampTime);
When i get my cursor on the edge of the screen (for example (1,1) in ViewPortPoint coordinates), the player is barely visible. I want to set maximum value for cursor's position. For example (1,1) will be the same as (0.8, 0.8) so the whole player is always visible.
Thank you for your attanetion!
Answer by Jessespike · Apr 21, 2016 at 09:55 PM
Replace Input.mousePosition with a new Vector3 that consists of Input.mousePosition with screen size calculations.
float maxScreenPoint = 0.8f;
Vector3 mousePos = Input.mousePosition * maxScreenPoint + new Vector3(Screen.width, Screen.height, 0f) * ((1f - maxScreenPoint) * 0.5f);
//Vector3 position = (target.position + GetComponent<Camera>().ScreenToWorldPoint(Input.mousePosition)) / 2f;
Vector3 position = (target.position + GetComponent<Camera>().ScreenToWorldPoint(mousePos)) / 2f;
Vector3 destination = new Vector3(position.x, position.y, -10);
transform.position = Vector3.SmoothDamp(transform.position, destination, ref velocity, dampTime);
Thank you so much for the extended help! This is exactly what i needed
Answer by DageLV · Aug 01, 2018 at 07:38 AM
Soo... How do i make this script work? I copy/paste the code in unity and i just get compiler errors. Anyone knows how to make the script actually work?
Quite easy actually. Read the script, make sure you undersand it. Add the couple variables that are missing. Read the errors you get and fix them. $$anonymous$$ake sure that it is called upon the correct object (players & cameras) and voilà, working like a charm, and smoothly as it is !
Your answer
