- Home /
How can you move a camera a set amount of units based on the player's x position in a 2d game?
Hi, I am still new to unity so sorry is this sounds like a stupid question.
I am trying to make a 2d game where if the player is inside the camera, the camera is still, however once the player moves to the edge of the camera, the camera move a set amount of units towards the edge that the player is at. However, I am currently encountering some errors. The script that I made goes as follows:
using System.Collections; using System.Collections.Generic; using UnityEngine;
public class CameraMovement : MonoBehaviour {
public GameObject Player;
public GameObject Camera;
//Half camera size is 12 units
public int Halfcamera = 12;
//how much the camera moves
public int CameraMove = 22;
void Start()
{
}
// Update is called once per frame
void Update()
{
if (Player.tranform.position.x > (Camera.transform.position.x + Halfcamera))
{
Camera + CameraMove;
}
else if (Player.transform.position.x < (Camera.transform.position.x - Halfcamera))
{
Camera - CameraMove;
}
}
}
If there is something wrong that I am doing then please inform me, any help is appreciated.,
Answer by Ymrasu · Aug 12, 2020 at 07:20 AM
You should be careful in what you name your variables, Camera is already used by a Class; The convention is that variable names start with a lowercase and Class names start with Uppercase. Another error you are getting is that you can not add the camera (GameObject) and a number (int) together; You need to access the position of the camera through it's transform (transform.position) and convert the number into a Vector3 to match the position's type.
The camera can be access through it's class (Camera.main) instead of making a variable for it. The camera can convert the player's world position into something easier to manage with the camera, in this case we can convert it to a viewport point (WorldToViewportPoint()). You can think of the viewport in terms of percentage of the screen (0 to 1); so if the converted player's position is less than 0 or if it is greater than 1, he is off screen.
Here is a way you could do it:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CameraMovement : MonoBehaviour
{
public GameObject player;
public int cameraMoveAmount = 22;
void Update()
{
// convert player position to a viewport point
var playerViewportPosition = Camera.main.WorldToViewportPoint(player.transform.position);
// is the player offscreen to the right?
if (playerViewportPosition.x > 1f) {
Camera.main.transform.position += Vector3.right * cameraMoveAmount; // move right by move amount
}
// is the player offscreen to the left?
else if (playerViewportPosition.x < 0f) {
Camera.main.transform.position += Vector3.left * cameraMoveAmount; // move left by move amount
}
}
}
Thanks! This helped me a lot with my camera problems.